import { Component, OnInit } from '@angular/core'
import { FadeInTop } from '../../shared/animations/fade-in-top.decorator'
import { JsonApiService } from 'app/core/api/json-api.service'
import { NotificationService } from '../../shared/utils/notification.service'
import { config } from '../../shared/smartadmin.config'
import { Router, ActivatedRoute } from '@angular/router' //路由引入

declare var $: any
declare var BMap: any
declare var echarts: any
declare var toMapPoint: any
declare var INFOBOX_AT_TOP

function stringify(value: any) {
  let stringifiedValue: any
  try {
    stringifiedValue = JSON.stringify(value)
  } catch {
    stringifiedValue = null
    console.warn(`stringify error, value: ${value}`)
  }
  return stringifiedValue
}

function parse(content: string) {
  let value: any
  try {
    value = JSON.parse(content)
  } catch {
    value = null
  }
  return value
}

function setLocal(key: string, value: any) {
  const valueString = stringify(value)
  localStorage.setItem(key, valueString)
  if (valueString === null) {
    removeSession(key)
  }
}

function getLocal(key: string) {
  const content = localStorage.getItem(key)
  const value = parse(content)
  return value
}

function removeSession(key: string) {
  localStorage.removeItem(key)
}

@FadeInTop()
@Component({
  selector: 'sa-data-optimization',
  templateUrl: './data-optimization.component.html',
  styleUrls: ['./data-optimization.css', './timeline.css']
})
export class DataOptimizationComponent implements OnInit {
  constructor(
    private jsonApiService: JsonApiService,
    private notificationService: NotificationService,
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {
    activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams) {
        this.jumpData = queryParams
      }
      // 订单监控跳转过来的数据
      if (common.getCookie('jumpFromOrderManagenment')) {
        this.jumpData = JSON.parse(common.getCookie('jumpFromOrderManagenment'))
        common.clearCookie('jumpFromOrderManagenment')
      }

      //从地磅数据验证跳转过来
      if (common.getCookie('weighbridgeDataResult')) {
        this.jumpData = JSON.parse(common.getCookie('weighbridgeDataResult'))
        common.clearCookie('weighbridgeDataResult')
      }

      // 从信息汇总跳转过来的数据
      const summaryInfoParams = JSON.parse(common.getCookie('jumpFromSummaryInfo'))
      if (summaryInfoParams) {
        const date = new Date()
        const endDate = common.getTimeMmss(date)
        date.setDate(date.getDate() - 1)
        const startDate = common.getTimeMmss(date)

        this.jumpData = {
          deviceId: summaryInfoParams.deviceId,
          startDate,
          endDate
        }
        common.clearCookie('jumpFromSummaryInfo')
      }
    })
  }

  // select2左滑切换
  carIndexMsg: any = {
    allNums: 0,
    index: 1,
    status: false
  }

  alertChartModelInfo: any = {} //echart异常警报信息模板信息
  versionChartModuleInfo: any = {} //echart固件升级信息模板信息
  coefChartModuleInfo: any = {} //echart系数设置信息模板信息
  companyChartModuleInfo: any = {} //echart厂区在线信息模板信息
  jumpData: any
  isAllowPre: boolean = false
  isAllowNext: boolean = false

  myMap: any
  apiType = '1' //api接口
  lookSignal = true //是否查看信号的条件
  loadometer = false //是否查地磅信息的条件
  linetoMap = false //是否选择地图联动的条件
  carSpeed = true //是否查看速度的条件
  showModify = true //显示修正数据
  questionRecord = true //问题记录
  versionNumber = true //版本号
  sensorChannel: boolean = false //记录损坏传感器开关
  voltage: boolean = false //设备电压信息开关
  deviceStatus: boolean = true //设备状态开关
  versionMessage = {
    name: '',
    alarmType: '',
    versionString: '',
    runStatus: '',
    carUploadDate: '',
    gpsUploadDate: '',
    updateTime: '',
    isShowGPS: false
  } //版本信息
  isGetRecord: any = { status: false } //子组件是否请求问题记录数据

  recordTime = ''
  filterTime = ''
  filterTimeDefault: number
  multiple = 1
  magnificationArr = [1000, 5000, 10000, 100000] //重量放大倍数
  startTime = ''
  endTime = ''
  startProblemTime = ''
  endProblemTime = ''
  problemStartTime = ''
  problemEndTime = ''
  companyId = ''
  selectedCompanyName = ''
  selectedCompanyId = ''

  inpSelect = '' //点击折线获取时间 选中的输入框
  zeroBeforeDate = ''
  upStartDate = ''
  upEndDate = ''
  downStartDate = ''
  downEndDate = ''
  zeroAfterDate = ''

  carNumber = ''
  carList = []
  companyList = []
  companyNameArr = []
  companyName = ''
  deviceId = '' //设备ID
  startDate = '' //开始时间
  endDate = '' //结束时间
  waveWeight = '1.0' //波动范围

  myChart: any
  allData = [] //echart图后台请求回来的数据
  passageData = [] //所有chart图折线的数组
  linetoMapData = [] //地图联动画轨迹数据
  loadometerData = [] //后台返回的地磅数据
  loadometerArr = [] //拼接成echart数组
  weightArr = [] //重量折线的数据
  carSpeedArr = [] //速度折线的数据
  passageName = [] //ad信号折线名
  passageArr = [] //ad信号数据
  voltageData: any = [] //设备电压数据,echart显示电压曲线
  voltageDataEchart: any = [] //设备电压数据,处理后数据

  errorRateArr = [] //记录误差率
  errorValueArr = [] //记录误差值
  poundWeight = 0 //当前地磅重量
  errorRate: any = 0 //当前误差率
  errorValue = 0 //当前误差值
  signal16Arr = [] //16通道的数据
  ad16Value = 0 //对应地磅数据的16通道的信号误差值
  ad16Rate: any = 0 //对应地磅数据的16通道的信号值的误差率
  isRate16 = false //是否计算16通道的误差率

  moveCanvasLayer: any //轨迹移动添加点图层
  carMoveCanvasLayer: any //移动折线对应地图添加点的图层,

  abnormalInfo //地图上的异常警报窗口

  sensorTableData: any = [] //传感器损坏模块table数据
  startTime_sensor: string = '' //损坏传感器开始时间
  endTime_sensor: string = '' //损坏传感器结束时间
  sensorList: any = [] // 设备事件模块中的传感器通道问题数组
  otherData: any = {} // 设备事件模块中的其他数据 弥补之前的接口数据不足
  renewalInfo: any = '' // 车辆的续费信息
  sensorArr: any = [
    {
      id: 1,
      text: '通道1',
      checked: false
    },
    {
      id: 2,
      text: '通道2',
      checked: false
    },
    {
      id: 3,
      text: '通道3',
      checked: false
    },
    {
      id: 4,
      text: '通道4',
      checked: false
    },
    {
      id: 5,
      text: '通道5',
      checked: false
    },
    {
      id: 6,
      text: '通道6',
      checked: false
    },
    {
      id: 7,
      text: '通道7',
      checked: false
    },
    {
      id: 8,
      text: '通道8',
      checked: false
    },
    {
      id: 9,
      text: '通道9',
      checked: false
    },
    {
      id: 10,
      text: '通道10',
      checked: false
    },
    {
      id: 11,
      text: '通道11',
      checked: false
    },
    {
      id: 12,
      text: '通道12',
      checked: false
    },
    {
      id: 13,
      text: '通道13',
      checked: false
    },
    {
      id: 14,
      text: '通道14',
      checked: false
    },
    {
      id: 15,
      text: '通道15',
      checked: false
    },
    {
      id: 16,
      text: '通道16',
      checked: false
    }
  ]
  private isMoveFlag: boolean = true //防抖节流，控制mousemove触发频率
  //	powerOffAlertList:any = [];//断电异常数据集合

  //重量y轴线
  yAxiWeight: any = {
    show: true,
    name: '重量',
    type: 'value',
    position: 'left',
    min: undefined,
    max: undefined,
    offset: undefined,
    axisLine: {
      lineStyle: {
        color: 'gray'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  }

  //信号y轴线
  yAxiSignal: any = {
    show: false,
    name: '信号',
    splitLine: {
      show: false
    },
    type: 'value',
    position: 'right',
    min: undefined,
    max: undefined,
    offset: undefined,
    axisLine: {
      lineStyle: {
        color: '#5c427c'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  }

  //速度y轴线
  yAxiSpeed: any = {
    show: false,
    name: '速度 KM/H',
    splitLine: {
      show: false
    },
    type: 'value',
    min: undefined,
    max: undefined,
    offset: 60,
    position: 'right',
    axisLine: {
      lineStyle: {
        color: '#5793f3'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  }

  //	指定图表的配置项和数据
  echartOption = {
    //		title: {
    //			left: '2%',
    //			top: '0px',
    //			text: '车载重量'
    //		},
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross' //十字星
      },
      formatter: function (params) {
        if (this.linetoMap) {
          var paramIndex = params[0].dataIndex
          var pointObj = this.linetoMapData[paramIndex]
          if (!pointObj || pointObj.x == '' || pointObj.x == '0' || pointObj.x == '0.0') {
            return
          }
          this.lineMoveCarPoint(pointObj)
        }

        if (!window.event) {
          return
        }
        if (!window.event.type) {
          return
        }
        var triggerType = window.event.type //触发类型
        var str = this.inpSelect
        if (triggerType == 'click') {
          this.recordTime = params[0].name
          if (!str) return
          this[str] = params[0].name
          if (str == 'downEndDate' || str == 'upStartDate') {
            if (startime1 == '' || endTime1 == '') {
              return
            }
            if (this.loadometerData.length > 0) {
              var startime1 = this.changeTime(this.upStartDate)
              var endTime1 = this.changeTime(this.downEndDate)
              for (var j = 0; j < this.loadometerData.length; j++) {
                var contrastTime = this.changeTime(this.loadometerData[j].date)
                if (startime1 < contrastTime && contrastTime <= endTime1) {
                  $('#weight').val(Math.floor(+this.loadometerData[j].weight * 10) / 10)
                  break
                }
              }
            }
          }
        }
        let res = ''
        const len = params.length
        for (let i = 0; i < len; i++) {
          if (params[i].seriesName === '网络离线') continue
          res = res + params[i].marker + params[i].seriesName + ':' + params[i].data + '</br>'
        }
        return res
      }.bind(this)
    },
    grid: {
      left: '54px',
      right: '100px',
      top: '100px'
    },
    toolbox: {
      feature: {
        dataView: {
          show: false,
          readOnly: false
        },
        restore: {
          show: false
        },
        saveAsImage: {
          show: false
        }
      }
    },
    legend: {
      selected: {},
      icon: 'circle'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: [this.yAxiWeight],

    dataZoom: [
      {
        realtime: true
      },
      {
        type: 'inside',
        realtime: true
      }
    ],
    series: [
      {
        name: '重量',
        type: 'line',
        //			itemStyle: {
        //				color: 'red'
        //			},
        data: []
      }
    ]
  }

  isDisable = true
  coefficientList = []
  coefCarStatus = 'offline'
  coefCarNumber = ''

  proTypeOptions = [] //存储问题记录分类选项描述
  proSlectedItem: any //记录选中一类时的数据,渲染页面选项
  proTypeParams: any = {
    //存储用户操作选择的数据
    problemType: '', //问题类型
    problemClass: '', //问题分类
    phenomenon: '', //问题现象
    repairGuide: '', //维修指导
    repairWay: '', //维修方式
    pheDescribe: '' //现象描述
  }
  seneorPhenlist = []

  hideOrshowline = []
  legendSleced: any = {}
  carIndexMess = {
    allNums: 0,
    index: 1,
    status: false
  }
  /**
   * 通道 安装位置
   */

  sensorAxleFront: any = [] //通道前
  sensorAxleAfter: any = [] //通道后
  installArray: any = [] //安装位置
  checkChannel: any = [] //选中通道数组
  ChannelLen: any = '' //原始轴的个数
  // gps选项
  gpsOptions = allSelectOptionsObj.gpsOptions
  // gsm选项
  gsmOptions = allSelectOptionsObj.gsmOptions
  haveRepaireObj: any = {} // 已维修返回的对象  system/getDeviceBaseInfoByDeviceId.html这个接口请求后存在对象中方便不同的方法使用这个对象
  message(data) {
    this.notificationService.smallBox({
      content: data,
      timeout: 3000
    })
  }
  confirm_message(message) {
    return new Promise(
      function (resolve, reject) {
        this.notificationService.smartMessageBox(
          {
            title: '提示',
            content: message,
            buttons: '[确认][取消]'
          },
          ButtonPressed => {
            if (ButtonPressed === '确认') {
              resolve()
            }
            if (ButtonPressed === '取消') {
              this.notificationService.smallBox({
                content: '操作取消',
                timeout: 3000
              })
              return
            }
          }
        )
      }.bind(this)
    )
  }
  searchTimer: any
  //设备ID自己更改时候 公司数据以及车辆数据也相应的更新
  deviceIdChange(e) {
    let that = this
    var key = e.target.value

    this.searchTimer && clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      if (that.selectRowData.deviceId || that.carNumber) {
        if (that.selectRowData.deviceId != key) {
          $('#companyTree .s_del_icon').click()

          that.deviceId = key
          that.selectRowData.deviceId = key
        }
      }
    }, 1000)
  }
  //公司选中回调
  companySelected(val) {
    this.deviceId = val.deviceId
    this.carNumber = val.carNumber
    this.selectedCompanyId = val.companyId
    this.selectedCompanyName = val.companyName
    this.selectRowData.companyId = val.companyId
    this.selectRowData.companyName = val.companyName
    this.selectRowData.deviceId = val.deviceId
    this.selectRowData.carNumber = val.carNumber
    if (val.carNumber && this.carNumberWeight) {
      this.carNumberWeight = ''
      //采用简单粗暴的方法清除;官方推荐的方法失效
      var str = $("<span class='select2-selection__placeholder'>请选择</span>")
      $('#loadometerSelect').val('')
      $('#select2-loadometerSelect-container').empty()
      $('#select2-loadometerSelect-container').attr('title', '')
      $('#select2-loadometerSelect-container').prepend(str)
      this.carIndexMsg.status = false //清空磅单数量
    }
    if (!this.selectedCompanyId) {
      var selectObj = $('#loadometerSelect')
      this.clearSelect2(selectObj) //清除Select中的数据
      this.carIndexMsg.status = false //清空磅单数量
    } else {
      if (val.companyClickFlag) {
        this.queryCarListByCompanyId()
      }
    }
    //组件车辆上下键事件生效,清除父级冲突的上下键盘事件
    if (val.clearKeyCodeEvent && val.carNumber) {
      document.body.onkeydown = null
    }
    //组件enter监听
    if (val.enterEventFlag) {
      this.showChart()
    }

    //清空算法问题
    for (let lis of this.algorithmQuestionList) {
      lis.selected = false
    }
  }
  //获取传感器参数
  getVersionMessage() {
    if (!this.versionNumber) return
    if (!this.deviceId) return
    this.versionMessage = {
      name: '',
      alarmType: '',
      versionString: '',
      runStatus: '',
      carUploadDate: '',
      gpsUploadDate: '',
      updateTime: '',
      isShowGPS: false
    }
    let reqdata = 'deviceId=' + this.deviceId
    this.hideOrshowline = []
    this.jsonApiService.http('system/getRealTimeData.html', reqdata).subscribe(result => {
      if (!result.success) return
      this.versionMessage.name = result.data.version
      this.versionMessage.runStatus = result.data.runStatus
      this.versionMessage.carUploadDate = result.data.carUploadDate
      this.versionMessage.gpsUploadDate = result.data.gpsUploadDate
      this.versionMessage.updateTime = result.data.updateTime
      if (result.data.alarmType == '1' || result.data.alarmType == '2') {
        this.versionMessage.alarmType = '[断电中]'
      } else if (result.data.runStatus == '0' && (result.data.alarmType == '0' || !result.data.alarmType)) {
        //20210227 陈柏良 设备离线，并且无警报时，才显示未知原因
        this.versionMessage.alarmType = '[未知原因]'
      } else if (result.data.runStatus == '0' && result.data.alarmType == '3') {
        //20210227 陈柏良 设备离线，才显示异常断电
        this.versionMessage.alarmType = '[异常断电]'
      } else if (result.data.alarmType == '4' && result.data.runStatus == '1') {
        this.versionMessage.alarmType = '[回传数据]'
      }
      if (this.versionMessage.carUploadDate && this.versionMessage.gpsUploadDate) {
        let abs = Math.abs(
          common.mmsstoTimestamp(this.versionMessage.carUploadDate) -
          common.mmsstoTimestamp(this.versionMessage.gpsUploadDate)
        )
        abs >= 30 * 60 * 1000 ? (this.versionMessage.isShowGPS = true) : (this.versionMessage.isShowGPS = false)
      }
      let coefArr = []
      if (!result.data.coef) return
      for (let i = 0; i < result.data.coef.length; i++) {
        let item = result.data.coef[i]
        if (item) {
          let vname = '通道' + (i + 1)
          coefArr.push(vname + ':' + item)
          this.hideOrshowline.push(vname)
        }
      }
      let resultString = ''
      for (let _i = 0; _i < coefArr.length; _i++) {
        if (_i < coefArr.length - 1) {
          resultString += coefArr[_i] + ','
        } else {
          resultString += coefArr[_i]
        }
      }
      this.versionMessage.versionString = resultString

      // 初始化传感器问题和Gps问题
      this.initSensorGps()
    })
  }
  keyCodeEvent() {
    document.body.onkeydown = null
    document.onkeydown = null
    document.body.onkeydown = function (event) {
      var e = event || window.event || arguments.callee.caller.arguments[0]
      if (e && this.loadometer) {
        //地磅数据勾选情况下才触发keydown事件
        if (e.keyCode == 38) {
          this.nextCarLoad('pre')
          return false
        }
        if (e.keyCode == 40) {
          this.nextCarLoad('next')
          return false
        }
        if (e.keyCode == 13) {
          this.showChart()
          return false
        }
      }
    }.bind(this)
  }

  msgHistoryList: any[] = []
  ngOnInit() {
    // 榜单数据
    let that = this
    // 获取缓存的群信息历史数据
    const msgHistory = getLocal('hd-optimization-msgHistory')
    this.msgHistoryList = msgHistory || []

    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        that.selectLoadometer() //初始化select 2 榜单
      })
    })
    if (this.inputParam.length == 0) {
      this.querySensor()
    } // 请求传感器列表接口
    this.getGpsInfo() //请求天线配置接口
    this.tableMove()
    this.initProTypeOptions()
    this.initCoefficientList()
    this.initDate().then(() => {
      if (this.jumpData && this.jumpData.deviceId) {
        if (this.jumpData.transportEndDate) {
          this.startTime = this.jumpData.transportStartDate
          this.endTime = this.jumpData.transportEndDate
        } else {
          this.startTime = this.jumpData.startDate
          this.endTime = this.jumpData.endDate
        }
        $('#datetimepicker1').val(this.startTime)
        $('#datetimepicker2').val(this.endTime)
        this.deviceId = this.jumpData.deviceId
        this.carNumber = this.jumpData.carNumber ? this.jumpData.carNumber : ''
        setTimeout(
          function () {
            $('#carNumberSelect2').val(this.deviceId).trigger('change')
            var str = $("<span class='select2-selection__rendered'>" + this.carNumber + '</span>')
            $('#carNumberSelect2').val('')
            $('#select2-carNumberSelect2-container').empty()
            $('#select2-carNumberSelect2-container').attr('title', '')
            $('#select2-carNumberSelect2-container').prepend(str)
          }.bind(this),
          100
        )
        this.showChart()
      }
    })
    //初始化创建一个空的信息窗口
    const content =
      '<div class="massageDiv">' +
      '<p class="p1">（KM/H）</span></p>' +
      '<div class="content">' +
      '<div class="contentImage"><div class="contentImage-img"><img src="assets/img/trackImage/positionInfo4.png"></div></div>' +
      '<div class="contentText">' +
      '<p><span class="leftSpan">经度：</span><span class="rightSpan"></span></p>' +
      '<p><span class="leftSpan">纬度：</span><span class="rightSpan"></span></p>' +
      '<p><span class="leftSpan">载重量：</span><span class="rightSpan"></span></p>' +
      '<p><span class="leftSpan">更新时间：</span><span class="rightSpan"></span></p>' +
      '</div></div>' +
      '</div>'
    const opts = {
      width: 400,
      heigth: 300
    }
    const infoWindow = new BMap.InfoWindow(content, opts)
    this.myChart = echarts.init(document.getElementById('chart'))
    this.initChart()
    window.onresize = function () {
      setTimeout(() => {
        that.myChart.resize()
      }, 120)
    }
    this.myChart.on(
      'click',
      function (params) {
        if (params.componentType === 'markPoint') {
          if (params.name == '离线警报' || params.name == '断电警报') {
            if (this.linetoMap) {
              var pointObj = params.data
              if (!pointObj || pointObj.lng == '' || pointObj.lat == '0') {
                this.message('经纬度异常')
                return
              }
              this.createAbnormalInfo(pointObj)
            }
          }
        } else {
          var pointObj = that.allData[params.dataIndex]
          if (pointObj == undefined) {
            return
          }
          var geturl = config.BaseURL
          pointObj.companyName = that.selectedCompanyName
          if (that.mapClick) {
            common.createInfoBox(that.myMap, pointObj, geturl)
            that.mapClick = false
            setTimeout(() => {
              that.mapClick = true
            }, 300)
          }
        }
      }.bind(this)
    )
    let map = new BMap.Map('allmap', { enableMapClick: false }) //创建地图实例
    let point = new BMap.Point(116.404, 39.915) //创建点坐标
    map.centerAndZoom(point, 15) //初始化地图，设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
    map.disableDoubleClickZoom() //禁用双击放大
    this.myMap = map
    // 车辆选择框发生改变触发
    // notice 这个 select 在 sa-company-tree-car-btn 组件中
    // companySelected 也能拦截到，天才想法单独绑定 change
    $('#carNumberSelect2').on('change', e => {
      // var data = e.params.data;
      if (e.target.value) {
        this.deviceId = e.target.value
        this.initSensorGps()
        this.getRenewTime()
        this.getVersionMessage()
      }
    })

    // $(document).mouseup(function(e){
    // 	  var _con = $('.holdImg');   // 设置目标区域
    // 	  var _holdOpenImg = $('.holdOpenImg');
    // 	  if(_holdOpenImg.is(e.target)){
    // 		if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
    // 			that.isHold = true
    // 		}
    // 	  }

    // });

    // this.dragDrop() // 拖拽工具箱
  }
  ngOnDestroy() {
    // 清除自动重置 ID 的定时器
    this.requestTimer && clearInterval(this.requestTimer)
    this.requestTimer = null
    document.onclick = null
    document.onkeydown = null
    document.body.onkeydown = null
    window.onresize = null
  }
  /**
   * 自动重置 ID 功能
   */
  // 自动重置ID设备基础展示信息
  autoResetBase = {
    freqNum: null, // 上传频率
    hwVersion: '', // 硬件版本
    coefficient: '', // 当前系数
    version: '' // 算法版本
  }

  // 全局保存轮询定时器
  requestTimer = null
  // 自动重置 ID 中新的 deviceId
  autoResetDeviceId = ''
  // 是否在轮询，轮询中禁止按钮操作
  isRequesting = false
  // 是否展示状态标识，操作中才展示进度 icon
  statusIcon = false
  // 当前请求的状态
  autoResetState = {
    frequencyStatus: 3,
    hwVersionStatus: 3,
    coefStatus: 3,
    binStatus: 3,
    binContent: '', // 升级信息
    step: '', // 升级进度，需要展示当前进行到第几步，也即 loopQueue 中的 text
    errMsg: '' // 失败信息
  }
  // 步骤的枚举
  loopQueue = [
    { key: 'frequencyStatus', text: '上传频率' },
    { key: 'hwVersionStatus', text: '硬件版本' },
    { key: 'coefStatus', text: '当前系数' },
    { key: 'binStatus', text: '算法版本' }
  ]

  TIME_COUNT = 9 * 60 // 自动重置ID轮询超时秒数

  openAutoResetView() {
    // 如果没有选择车辆不能操作
    if (!this.deviceId) {
      this.jsonApiService.message('请选择车辆')
      return
    }

    // 拉取设备当前信息
    const autoResetBase = this.autoResetBase
    const reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=2'
    // 查询上传频率，没有默认 10
    this.jsonApiService.http('car/getFactoryAndProject.html', reqdata).subscribe(result => {
      if (result.success) {
        autoResetBase.freqNum = result.data
      } else {
        autoResetBase.freqNum = 10
      }
      $('#autoResetModal').show()
    })
    // 查询设备其他信息
    this.jsonApiService
      .http_obj('system/getDeviceBaseInfoByDeviceId.html', {
        deviceId: this.deviceId
      })
      .subscribe(data => {
        if (data.success && data.data) {
          const { hwVersion, version, sensorChannel, coef } = data.data
          autoResetBase.hwVersion = hwVersion
          autoResetBase.version = version
          if (!sensorChannel || sensorChannel.length < 1) {
            autoResetBase.coefficient = ''
            return
          }
          let result = sensorChannel.reduce((acc, current) => {
            let temp = acc
            if (Number(current) !== 0 && coef[Number(current) - 1] !== 0) {
              temp =
                acc !== ''
                  ? acc + ',' + `CH${current}:${coef[Number(current) - 1]}`
                  : `CH${current}:${coef[Number(current) - 1]}`
            }
            return temp
          }, '')
          autoResetBase.coefficient = result.length === 0 ? '' : '[' + result + ']'
        }
      })
  }

  //设备版本升级
  versionUpdate() {
    // 如果没有选择车辆不能操作
    if (!this.deviceId) {
      this.jsonApiService.message('请选择车辆')
      return
    }
    this.jsonApiService.confirm_message('您确定要进行设备版本升级？').then(() => {
      let reqdata = 'deviceId=' + this.deviceId
      this.jsonApiService.http('bininfoForOM/getBinInfoByDeviceId.html', reqdata).subscribe(data => {
        if (data.success) {
          let reqdata =
            'protocolVersion=' +
            data.data.protocolVersion +
            '&deviceId=' +
            this.deviceId +
            '&binId=' +
            data.data.binId
          this.jsonApiService.http('system/upgradeonline.html', reqdata).subscribe(data => {
            this.jsonApiService.message(data.message)
          })
        } else {
          this.jsonApiService.message(data.message)
        }
      })
    })
  }

  closeDeviceModal() {
    $('#autoResetModal').hide()
    // 清空选中的新设备
    this.autoResetDeviceId = ''
    // 清空展示设备信息
    this.autoResetBase = {
      freqNum: null,
      hwVersion: '',
      coefficient: '',
      version: ''
    }
    // 清空升级信息状态
    this.statusIcon = false
    this.requestTimer && clearInterval(this.requestTimer)
    this.requestTimer = null
    this.isRequesting = false
    this.autoResetState = {
      frequencyStatus: 3,
      hwVersionStatus: 3,
      coefStatus: 3,
      binStatus: 3,
      binContent: '',
      step: '',
      errMsg: ''
    }
  }
  // 新设备ID搜索关键字
  autoResetSearchKey = ''
  // 选中的DeviceId
  selectedDeviceId = ''
  // 搜索结果列表数据
  resetDeviceTableList = []
  // 搜索结果页脚信息
  totalCountDevice: number = 0
  pageSizeDevice: number = 10
  curPageDevice: number = 1

  showSelectModal(modal) {
    // 正在请求，不能操作
    if (this.isRequesting) {
      return
    }
    // 重置状态
    this.autoResetSearchKey = ''
    this.selectedDeviceId = ''
    this.resetDeviceTableList = []

    this.totalCountDevice = 0
    this.pageSizeDevice = 10
    this.curPageDevice = 1
    modal.show()
  }

  //分页回调
  paginateDevice(e) {
    this.curPageDevice = e.page + 1
    this.pageSizeTab = e.rows
    this.searchNewDeviceId()
  }

  refreshDevice() {
    this.totalCountDevice = 0
    this.pageSizeDevice = 10
    this.curPageDevice = 1
    this.searchNewDeviceId()
  }
  // 搜索新的设备
  searchNewDeviceId() {
    if (this.autoResetSearchKey.length < 3) {
      this.jsonApiService.message('新的主机ID不能少于三位')
      return
    }
    let data = {
      pageSize: this.pageSizeDevice,
      nowPage: this.curPageDevice,
      parameters: {
        searchKey: this.autoResetSearchKey,
        online: '0'
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('system/realTimeData.html', reqdata).subscribe(result => {
      if (!result.isSuccess) {
        this.jsonApiService.message(result.message)
        return
      }
      // 设置选中状态，车辆列表需要选择
      for (let item of result.exhibitDatas) {
        item.isChecked = false
      }

      this.resetDeviceTableList = result.exhibitDatas
      this.totalCountDevice = result.recordCount
    })
  }

  //选中
  rowDeviceSelected(event, i) {
    // click 事件是在选中效果改变后触发的
    // 选中状态为 true，当前选中项是新选中的
    // 可能是切换选中项，所以需要修改其他的选中状态
    if (event.target.checked) {
      this.resetDeviceTableList.forEach((item, index) => {
        if (index === i) {
          this.selectedDeviceId = item.deviceId
          item.isChecked = true
        } else {
          item.isChecked = false
        }
      })
    } else {
      // 选中状态为 false，取消选中状态
      // 无需重置其他项
      this.selectedDeviceId = ''
    }
  }

  // 选择新的 deviceId
  selectDevice(modal) {
    this.autoResetDeviceId = this.selectedDeviceId
    modal.hide()
  }

  // 确认重置设备ID
  confirmDevice() {
    if (!this.autoResetDeviceId) {
      this.jsonApiService.message('请选择需要重置的设备')
      return
    }
    const self = this
    this.confirm_message('确定重置ID？')
      .then(() => {
        self.statusIcon = true
        $.ajax({
          url: config.BaseURL + 'system/uploadDeviceIdAuto.html',
          method: 'POST',
          xhrFields: {
            withCredentials: true
          },
          data: {
            carNumber: self.carNumber,
            deviceId: self.deviceId,
            newDeviceId: self.autoResetDeviceId
          }
        })

        // 提示清空，只有进行到算法版本才展示
        self.autoResetState.binContent = ''
        // 清空错误提示
        self.autoResetState.errMsg = ''
        // 首次重置状态为第一步
        self.autoResetState.step = ''

        // 所以状态为 loading
        self.loopQueue.forEach(step => {
          self.autoResetState[step.key] = 3
        })

        // 记录轮询状态
        self.isRequesting = true

        let timeCount = 0

        let hasFailed = { status: false }

        let allSuccess = { status: false }

        // 定时器中只负责清除定时器操作，所有失败提示在请求中处理
        self.requestTimer = setInterval(() => {
          // 超时或者请求失败, 和 请求全部成功 不需要再轮询
          // 没有失败请求，没有全部成功，继续请求
          if (!hasFailed.status && !allSuccess.status) {
            self.updateAuto.call(self, self.deviceId, timeCount, hasFailed, allSuccess)
          }

          if (timeCount > self.TIME_COUNT * 1000 || hasFailed.status || allSuccess.status) {
            self.isRequesting = false
            clearInterval(self.requestTimer)
            self.requestTimer = null
            return
          }
          timeCount += 5 * 1000
        }, 5000)
      })
      .catch(() => { })
  }

  updateAuto(deviceId, timeCount, hasFailed, allSuccess) {
    const that = this
    const autoResetBase = that.autoResetBase
    $.ajax({
      url: config.BaseURL + 'system/getStatusByUpLoadDeviceIdAuto.html',
      method: 'get',
      xhrFields: {
        withCredentials: true
      },
      data: { deviceId },
      success: function (res) {
        // res = JSON.parse(res)
        const { data: result } = res
        let code, message
        if (result) {
          code = result.code
          // 提示 message 需要给默认值
          // 若接口未返回，或请求失败，仍需提示
          message = result.message || '请求失败'
        }
        // 记录 loading 的状态
        // 超时后需要从 loading 的位置开始设置状态为失败
        let loadingIndex = that.loopQueue.length

        // 重新写入硬件版本和算法版本
        autoResetBase.hwVersion = result.hwVersion ? result.hwVersion : autoResetBase.hwVersion
        autoResetBase.version = result.binVersion ? result.binVersion : autoResetBase.version

        // 无 code 或 code 为0，即下发请求失败退出轮询 code(0失败 1成功)
        if (!code || code === 0) {
          that.autoResetState.binContent = ''
          // 请求失败需要将所以进行中和未开始的状态置为失败
          // 成功的状态保留
          that.loopQueue.forEach(step => {
            // 1成功 2失败 3执行中
            if (that.autoResetState[step.key] === 3) {
              // 如果是前面有成功的，当前执行中为失败
              hasFailed.status === false && (that.autoResetState.step = step.text)
              hasFailed.status = true
            }
            // 有失败，全部为失败循环修改状态
            if (hasFailed.status) {
              that.autoResetState[step.key] = 2
            }
          })
          // 无论状态如何，请求失败不再继续
          hasFailed.status = true
          that.autoResetState.errMsg = message
          that.jsonApiService.message(message)
          return
        }

        // 默认全部成功，如果有失败或加载中 置为 false
        // 全部成功也要停止轮询
        let successFlag = true
        that.autoResetState.binContent = result.binContent

        // 遍历有三种情况 1成功 2失败 3执行中
        // 成功需要继续遍历
        // 如果存在 loading 后续全为 loading
        // 默认是 loading 状态，所以遇到 loading 状态就可以跳出循环了
        // 如果存在失败后续全为失败
        for (let i = 0; i < that.loopQueue.length; i++) {
          const key = that.loopQueue[i].key
          const text = that.loopQueue[i].text
          // 将接口返回状态记录下来
          that.autoResetState[key] = result[key]
          // 如果前面已经有失败，就为失败 continue
          // 前面有失败，loading 变为失败，所以需要前置判断
          if (hasFailed.status) {
            // 由于前面存在失败，需要修改状态
            // 这里重置状态为失败
            that.autoResetState[key] = 2
            continue
          }
          // 如果是 loading，后续全为 loading
          // 状态默认是 loading 所以不需要继续循环
          if (result[key] === 3) {
            loadingIndex = i
            successFlag = false
            // 记录当前的操作步骤，请求发送失败时候用
            that.autoResetState.step = text
            break
          }
          if (result[key] === 2) {
            //存在失败后续全部失败
            hasFailed.status = true
            that.autoResetState.step = text
            that.autoResetState.errMsg = message
            successFlag = false
            that.jsonApiService.message(message)
          }
        }
        allSuccess.status = successFlag

        // 循环后判断超时 超时所有 loading 变为失败
        if (timeCount > that.TIME_COUNT * 1000) {
          that.autoResetState.step = that.loopQueue[loadingIndex].text
          that.autoResetState.errMsg = '重置ID操作超时'
          for (loadingIndex; loadingIndex < that.loopQueue.length; loadingIndex++) {
            const key = that.loopQueue[loadingIndex].key
            that.autoResetState[key] = 2
          }
        }
      },
      error: function (errorMsg) {
        // 这里使用上次请求记录的步骤
        that.autoResetState.errMsg = '发送请求失败'
        that.loopQueue.forEach(step => {
          that.autoResetState[step.key] = that.autoResetState[step.key] !== 1 ? 2 : that.autoResetState[step.key]
        })
        // 请求失败也是失败状态
        hasFailed.status = true
      }
    })
  }

  /**
   * 自动重置 ID 功能 ends
   */

  //初始化时间
  initDate() {
    let that = this
    return new Promise(function (resolve) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker1')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.startTime = time
              that.startProblemTime = time
              $('#datetimepicker2').datetimepicker('setStartDate', time)
              $('#datetimepicker1').change()
              if (that.selectedCompanyId && that.loadometer) {
                that.queryCarListByCompanyId()
              }
            })
          $('#datetimepicker2')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.endTime = time
              that.endProblemTime = time
              $('#datetimepicker1').datetimepicker('setEndDate', time)
              $('#datetimepicker2').change()
              if (that.selectedCompanyId && that.loadometer) {
                that.queryCarListByCompanyId()
              }
            })
          // $('#datetimepicker1')
          //   .datetimepicker({
          //     //时间插件
          //     format: 'yyyy-mm-dd hh:ii:ss',
          //     language: 'zh-CN',
          //     autoclose: true
          //   })
          //   .on('changeDate', function (e) {
          //     var date = e.date
          //     var time = common.getTimeMmss(date)
          //     that.startProblemTime = time
          //     $('#datetimepicker2').datetimepicker('setStartDate', time)
          //     $('#datetimepicker1').change()
          //   })
          // $('#datetimepicker2')
          //   .datetimepicker({
          //     //时间插件
          //     format: 'yyyy-mm-dd hh:ii:ss',
          //     language: 'zh-CN',
          //     autoclose: true
          //   })
          //   .on('changeDate', function (e) {
          //     var date = e.date
          //     var time = common.getTimeMmss(date)
          //     that.endProblemTime = time
          //     $('#datetimepicker1').datetimepicker('setEndDate', time)
          //     $('#datetimepicker2').change()
          //   })
          var date = new Date()
          let time1 = common.getTimeMmss(date)
          $('#datetimepicker2').val(time1) //当前时间
          that.endTime = time1
          that.endProblemTime = time1
          date.setDate(date.getDate() - 1) //设置前一周
          let time2 = common.getTimeMmss(date)
          $('#datetimepicker1').val(time2)
          that.startTime = time2
          that.startProblemTime = time2
          resolve(null)
        })
      })
    })
  }
  //删除所选日期
  del_date() {
    $('#datetimepicker1').val('')
    $('#datetimepicker2').val('')
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }
  // del_problemdate() {
  //   $('#datetimepicker1').val('')
  //   $('#datetimepicker2').val('')
  //   this.startProblemTime = ''
  //   this.endProblemTime = ''
  //   $('#datetimepicker1').datetimepicker('setStartDate', null)
  //   $('#datetimepicker2').datetimepicker('setEndDate', null)
  // }
  //初始化echart图
  initChart() {
    this.allData = [] //echart图后台请求回来的数据
    this.passageData = [] //所有chart图折线的数组
    this.linetoMapData = [] //地图联动画轨迹数据
    this.loadometerData = [] //后台返回的地磅数据
    this.loadometerArr = [] //拼接成echart数组
    this.weightArr = [] //重量折线的数据
    this.carSpeedArr = [] //速度折线的数据
    this.passageName = [] //ad信号折线名
    this.passageArr = [] //ad信号数据
    this.echartOption.xAxis.data = []
    this.echartOption.series = []
    this.myChart.setOption(this.echartOption, true)
  }



  //百度地图绘画路线,不带方向箭头,当前版本不用该函数
  drawTrack(map, param) {
    var pointArr = param
    map.clearOverlays()

    var linkPoint = []
    var linkPoint = [] //拼接线的折点

    for (var i = 0; i < pointArr.length; i++) {
      //    转换成百度坐标
      var mapPoint = toMapPoint(pointArr[i])
      if (mapPoint) {
        linkPoint.push(new BMap.Point(mapPoint.lng, mapPoint.lat))
      }
    }
    var polyline = new BMap.Polyline(linkPoint, {
      strokeColor: '#4169e1',
      strokeWeight: 6,
      strokeOpacity: 0.9
    }) //创建折线
    map.addOverlay(polyline)
    var starPoint = new BMap.Point(pointArr[0].lng, pointArr[0].lat)
    var endPoint = new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat)
    var opts = {
      position: starPoint, // 指定起点所在的地理位置
      offset: new BMap.Size(0, 0) //文本偏移量
    }
    var endOpts = {
      position: endPoint, // 指定终点点所在的地理位置
      offset: new BMap.Size(0, 0) //文本偏移量
    }
    var label = new BMap.Label('起点', opts) // 创建文本内容
    var endLabel = new BMap.Label('终点', endOpts) // 创建文本内容
    label.setStyle({
      color: 'red',
      fontSize: '12px',
      height: '20px',
      padding: '0px 30px 0 2px',
      margin: 0,
      lineHeight: '20px',
      fontFamily: '微软雅黑'
    })
    endLabel.setStyle({
      color: 'red',
      fontSize: '12px',
      height: '20px',
      padding: '0px 30px 0 2px',
      margin: 0,
      lineHeight: '20px',
      fontFamily: '微软雅黑'
    })
    map.addOverlay(label)
    map.addOverlay(endLabel)
    setTimeout(function () {
      map.centerAndZoom(new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat), 10)
    }, 10)
  }

  // * 时间格式检查
  checkDateTime(str) {
    var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/
    var r = str.match(reg)
    if (r == null) return false
    r[2] = r[2] - 1
    var d = new Date(r[1], r[2], r[3], r[4], r[5], r[6])
    if (d.getFullYear() != r[1]) return false
    if (d.getMonth() != r[2]) return false
    if (d.getDate() != r[3]) return false
    if (d.getHours() != r[4]) return false
    if (d.getMinutes() != r[5]) return false
    if (d.getSeconds() != r[6]) return false
    return true
  }
  //撤回
  recall() {
    var deviceId = this.deviceId
    var zeroBeforeDate = $('#zeroBeforeDate').val()
    var zeroAfterDate = $('#zeroAfterDate').val()
    if (deviceId == '') {
      this.message('请选择车牌号')
      return
    }
    if (!this.checkDateTime(zeroBeforeDate)) {
      this.message('上货前置零起始时间格式不正确或为空')
      return
    }
    if (!this.checkDateTime(zeroAfterDate)) {
      this.message('卸货后置零结束间格式不正确或为空')
      return
    }
    let that = this
    this.confirm_message('是否确认所有时间段没问题,然后开始撤销数据吗').then(() => {
      $.ajax({
        type: 'POST',
        url: config.BaseURL + 'system/recall.html',
        data: {
          deviceId: deviceId,
          upStartDate: zeroBeforeDate,
          downEndDate: zeroAfterDate
        },
        xhrFields: {
          withCredentials: true
        },
        dataType: 'json',
        success: function (result) {
          that.message(result.message)
        },
        error: function (errorMsg) {
          that.message('网络错误,请联系管理员')
        }
      })
    })
  }
  //判断时间是否在问题记录时间区间内
  timeInProblemStartEnd() {
    let result = true
    if (!this.startTime_problem || !this.endTime_problem) {
      this.jsonApiService.message('问题记录起始时间不能为空')
      result = false
      return result
    }
    let stNum_pb = common.mmsstoTimestamp(this.startTime_problem)
    let etNum_pb = common.mmsstoTimestamp(this.endTime_problem)
    if (!stNum_pb || !etNum_pb) {
      this.jsonApiService.message('问题记录起始时间格式不正确')
      result = false
      return result
    }

    let checkArr = [
      { name: '上货前置零起始时间', time: this.zeroBeforeDate },
      { name: '上货点起始时间', time: this.upStartDate },
      { name: '上货点结束时间', time: this.upEndDate },
      { name: '卸货点起始时间', time: this.downStartDate },
      { name: '卸货点结束时间', time: this.downEndDate },
      { name: '卸货后置零结束时间', time: this.zeroAfterDate }
    ]

    for (let item of checkArr) {
      if (item.time) {
        let _tn = common.mmsstoTimestamp(item.time)
        if (_tn < stNum_pb || _tn > etNum_pb) {
          this.jsonApiService.message(item.name + '需要在问题起始结束时间内')
          result = false
          break
        }
      }
    }
    return result
  }

  //数据优化提交
  makeData() {
    let exceptionType: any, proType: any
    if (!this.proTypeParams.problemType || !this.proTypeParams.problemClass) {
      this.jsonApiService.message('请选择问题分类')
      return
    }
    if (this.proTypeParams.problemType) {
      let operaParam = this.getSelectedVAL()
      proType = +this.proTypeParams.problemType + 1 + '0' + (+this.proTypeParams.problemClass + 1)
      if (operaParam.problemClassStr == '其他') {
        proType = +this.proTypeParams.problemType + 1 + '00'
      }
      exceptionType = +this.proTypeParams.problemType + 1
    }
    var deviceId = this.deviceId
    var upStartDate = $('#upStartDate').val()
    var upEndDate = $('#upEndDate').val()
    var weight = $('#weight').val()
    var downStartDate = $('#downStartDate').val()
    var downEndDate = $('#downEndDate').val()
    var zeroBeforeDate = $('#zeroBeforeDate').val()
    var zeroAfterDate = $('#zeroAfterDate').val()
    var startWeight = $('#startWeight').val()
    var endWeight = $('#endWeight').val()
    if (deviceId == '') {
      this.message('请选择车牌号')
      return
    }
    var isSumit = this.isAllDateTime()
    if (!isSumit) {
      return
    }
    var isWave = $('#isWave').prop('checked') //返回 true/false
    var isDiagonal = $('#isDiagonal').prop('checked') //上卸货曲线,返回 true/false
    let that = this

    if (zeroBeforeDate && upStartDate) {
      if (common.mmsstoTimestamp(zeroBeforeDate) - common.mmsstoTimestamp(upStartDate) > 0) {
        this.jsonApiService.message('上货前置零时间不能大于上货时间')
        return
      }
    }
    if (upStartDate && upEndDate) {
      if (common.mmsstoTimestamp(upStartDate) - common.mmsstoTimestamp(upEndDate) > 0) {
        this.jsonApiService.message('上货开始时间不能大于上货结束时间')
        return
      }
    }
    if (upEndDate && downStartDate) {
      if (common.mmsstoTimestamp(upEndDate) - common.mmsstoTimestamp(downStartDate) > 0) {
        this.jsonApiService.message('上货结束时间不能大于卸货开始时间')
        return
      }
    }
    if (downStartDate && downEndDate) {
      if (common.mmsstoTimestamp(downStartDate) - common.mmsstoTimestamp(downEndDate) > 0) {
        this.jsonApiService.message('卸货开始时间不能大于卸货结束时间')
        return
      }
    }
    if (downEndDate && zeroAfterDate) {
      if (common.mmsstoTimestamp(downEndDate) - common.mmsstoTimestamp(zeroAfterDate) > 0) {
        this.jsonApiService.message('卸货结束时间不能大于卸货后置零结束时间')
        return
      }
    }
    let isTime = this.timeInProblemStartEnd()
    if (!isTime) return
    this.confirm_message('是否确认所有时间段没问题，然后开始进行数据替换吗？').then(() => {
      layer.load()
      $.ajax({
        type: 'POST',
        url: config.BaseURL + 'system/makedata.html',
        xhrFields: {
          withCredentials: true
        },
        data: {
          deviceId: deviceId,
          upStartDate: upStartDate,
          upEndDate: upEndDate,
          weight: weight,
          downStartDate: downStartDate,
          downEndDate: downEndDate,
          isWave: isWave,
          zeroBeforeDate: zeroBeforeDate,
          zeroAfterDate: zeroAfterDate,
          isDiagonal: isDiagonal,
          startWeight: startWeight,
          endWeight: endWeight,
          waveWeight: that.waveWeight,
          exceptionType: exceptionType,
          programType: proType,
          orderId: ''
        },
        dataType: 'json',
        success: function (result) {
          that.message(result.message)

          layer.closeAll('loading')
        },
        error: function (errorMsg) {
          that.message('网络错误请联系管理员')
        }
      })
    })
  }
  //监听所有填写了的时间输入框的值必须为时间格式.
  isAllDateTime() {
    var result = true
    //		var isAllNull=true;//必要的2组时间是否为空,都为空的时候阻止掉
    //		var upStartDate=$('#upStartDate').val();//上货点起始时间
    //		var upEndDate=$('#upEndDate').val();//上货点结束时间
    //		var downStartDate=$('#downStartDate').val();//卸货点起始时间
    //		var downEndDate=$('#downEndDate').val();//卸货点结束时间
    var weight = $('#weight').val()
    if (weight == '') {
      result = false
      this.message('请输入重量值...')
      return result
    }
    //		if(this.checkDateTime(upStartDate)&&this.checkDateTime(upEndDate)){
    //			isAllNull=false;
    //		}
    //		if(this.checkDateTime(downStartDate)&&this.checkDateTime(downEndDate)){
    //			isAllNull=false;
    //		}
    //		if(isAllNull){
    //			//2组时间都为空
    //			this.message('上货点起始时间+上货点结束时间 或者卸货点起始时间+卸货点结束时间 必须要正确填写一组');
    //			result=false;
    //			return result;
    //		}
    //		else{
    //有一组时间填写要求正确,校验是否正确填写时间格式
    var messageVal = ''
    var that = this
    $('.getChartTime').each(function (index) {
      var indexVal = $(this).val()
      if (indexVal !== '') {
        if (!that.checkDateTime(indexVal)) {
          var mes = $(this).attr('placeholder').split('（')[0]
          messageVal = messageVal + mes + ' '
          result = false
        }
      }
    })
    if (messageVal !== '') {
      this.message(messageVal + '格式不正确')
    }
    return result
    //		}
  }
  //记录上卸货点
  recordTransportData() {
    var deviceId = this.deviceId
    var upStartDate = $('#upStartDate').val()
    var upEndDate = $('#upEndDate').val()
    var weight = $('#weight').val()
    var downStartDate = $('#downStartDate').val()
    var downEndDate = $('#downEndDate').val()
    var carNumber = this.carNumber
    if (deviceId == '') {
      this.message('请选择车牌号')
      return
    }
    var isSumit = this.isAllDateTime()

    if (!isSumit) {
      return
    }
    let that = this
    this.confirm_message('是否保存上卸货点').then(() => {
      $.ajax({
        type: 'POST',
        url: config.BaseURL + 'stats/recordtransportdata.html',
        xhrFields: {
          withCredentials: true
        },
        data: {
          deviceId: deviceId,
          upStartDate: upStartDate,
          upEndDate: upEndDate,
          weight: weight,
          downStartDate: downStartDate,
          downEndDate: downEndDate,
          carNumber: carNumber
        },
        dataType: 'json',
        success: function (result) {
          that.message(result.message)
        },
        error: function (errorMsg) {
          that.message('网络错误,请联系管理员')
        }
      })
    })
  }
  //定义转换时间戳函数
  changeTime(str) {
    let str1 = str.replace(/-/g, '/')
    let timestamp = new Date(str1).getTime()
    return timestamp
  }
  mapClick: boolean = true //地图点击防抖节流
  //生成echart折线图
  showChart() {
    if ($('#deviceDetailModal').attr('style').indexOf('display: block;') > 0) {
      //如果设备弹窗打开就刷新数据
      this.getDeviceInfoData()
      this.getTableDataTab(this.activeTab)
    }
    if (this.deviceId == '') {
      this.message('请选择需要查看的车辆')
      return
    }
    // 标记损坏传感器 选中拉取数据
    // 目前功能隐藏
    if (this.sensorChannel) {
      this.sensorLoad() //拉取损坏传感器数据
    }
    // 获取开始结束时间
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()
    if (this.startTime == '') {
      this.message('开始时间不能为空')
      return
    }
    if (this.endTime == '') {
      this.message('结束时间不能为空')
      return
    }
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 31)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    //设备基本信息,已过期则弹出提示框
    this.getDeviceBasicInfo(true)

    this.myMap.clearOverlays()
    function nullUpdate() { }
    this.carMoveCanvasLayer = new CanvasLayer({
      map: this.myMap,
      update: nullUpdate,
      zIndex: 10
    })
    this.moveCanvasLayer = new CanvasLayer({
      map: this.myMap,
      update: nullUpdate,
      zIndex: 10
    })
    this.myMap.addOverlay(this.carMoveCanvasLayer)
    this.myMap.addOverlay(this.moveCanvasLayer)
    this.askForData()
    // this.clickHold(false)// 自动展开工具箱
    this.gpsRecord = [] //GPS数据更新
  }
  //创建生成异常警报弹窗
  createAbnormalInfo(infoData) {
    infoData.onTime = infoData.onTime ? infoData.onTime : '无'
    if (this.abnormalInfo) {
      this.myMap.removeOverlay(this.abnormalInfo)
    }
    let point = new BMap.Point(infoData.lng, infoData.lat)
    //			this.myMap.centerAndZoom(point, 14);
    infoData.abType = infoData.type == '1' ? '主板开关机事件' : '主机上下电事件'
    //			let colseTime=infoData.totalSecond+'秒';
    //			if(infoData.totalSecond>60){
    //				colseTime = this.convertTime(infoData.totalSecond);
    //			}
    let lostWeightHtml = ''
    if (infoData.lostime) {
      lostWeightHtml =
        '<li><span class="leftSpan">重量丢失：</span><span class="rightSpan"> 约' +
        this.convertTime(infoData.lostime) +
        '</span></li>'
    }
    let html =
      '<div class="abInfobox infoBox">' +
      '<div class="title">' +
      infoData.carNumber +
      '异常信息</div>' +
      '<div class="content">' +
      '<ul>' +
      //						'<li><span class="leftSpan">所属公司：</span><span class="rightSpan"> '+infoData.companyName+'</span></li>'+
      '<li><span class="leftSpan">异常类型：</span><span class="rightSpan"> ' +
      infoData.name +
      '</span></li>' +
      '<li><span class="leftSpan">开始时间：</span><span class="rightSpan"> ' +
      infoData.offTime +
      '</span></li>' +
      '<li><span class="leftSpan">结束时间：</span><span class="rightSpan"> ' +
      infoData.onTime +
      '</span></li>' +
      '<li><span class="leftSpan">异常时长：</span><span class="rightSpan"> ' +
      infoData.rangeTime +
      '</span></li>' +
      //						lostWeightHtml+
      '<li><span class="leftSpan">发生地址：</span><span class="rightSpan"> ' +
      infoData.address +
      '</span></li>' +
      '</ul>' +
      '</div>' +
      '<div class="abpointer"></div>' +
      '</div>'
    this.abnormalInfo = new BMapLib.InfoBox(this.myMap, html, {
      boxStyle: {
        width: '240px',
        height: '0'
      },
      offset: new BMap.Size(240, 160),
      closeIconMargin: '12px 0px 0;z-index: 1;width: 18px',
      closeIconUrl: 'assets/img/trackImage/close1.png',
      enableAutoPan: true,
      align: INFOBOX_AT_TOP
    })
    let marker = new BMap.Marker(point)
    this.abnormalInfo.open(marker)
  }
  //传递子组件事件
  transferSubcomponent() {
    //传值子组件,是否获取问题记录数据
    if (this.questionRecord) {
      this.isGetRecord = {
        status: true,
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        carNumber: this.carNumber,
        startDate: this.startTime,
        endDate: this.endTime
      }
    } else {
      this.isGetRecord = { status: false }
    }
  }
  timeShadow: any = [] //没有历史数据区域
  isShowLoading: boolean = false //是否显示loading
  //后台获取数据
  askForData() {
    this.loadometerData = []
    this.loadometerArr = []
    this.voltageData = []
    let _reqdata =
      'deviceId=' +
      this.deviceId +
      '&startTime=' +
      this.startTime +
      '&endTime=' +
      this.endTime +
      '&showModify=' +
      this.showModify
    this.jsonApiService.http2('weighbridge/weightforreal.html', _reqdata).subscribe(result => {
      if (result.data.length >= 1) {
        this.loadometerData = result.data
      }
    })
    this.jsonApiService.http2('logForVoltage/queryLogForVoltageByParam.html', _reqdata).subscribe(result => {
      if (result.success) {
        this.voltageData = result.data
      }
    })
    this.initChart()
    //===============================================================计算在厂区=====================================================================================================
    // this.plantArea()
    // this.getCompanyRail()
    const reqdata =
      'deviceId=' +
      this.deviceId +
      '&startTime=' +
      this.startTime +
      '&endTime=' +
      this.endTime +
      '&showModify=' +
      this.showModify
    let getDateUrl = 'stats/draw.html'
    if (this.apiType == '2') {
      getDateUrl = 'system/gpsweightAPI.html'
    }
    var loseLongLatArray = []
    var latestPointData = null // 存储上一次有经纬度的点
    this.isShowLoading = true
    this.jsonApiService.http2(getDateUrl, reqdata).subscribe(data => {
      this.isShowLoading = false
      this.transferSubcomponent()
      this.getVersionMessage()
      this.getRenewTime()
      this.allData = data.data
      if (this.allData.length < 2) {
        this.message('没有数据')
        return
      }
      this.drawRailDeal()
      this.linetoMapData = [] //地图联动轨迹画线数据
      this.carSpeedArr = [] //画速度折线数据
      let timeValue = []
      let len = this.allData.length
      var lostWeight = [] //记录重量丢失的时间
      var lostWeightMark = [] //计算丢失重量的时长
      let nullGpsArr = [] //经纬度为空或者0.0的画折线数据
      var nullMarkerData = [] //计算经纬度丢失的时长
      let isLostGps = false //是否有丢失经纬度
      var isHavePoint = -1 //控制判断经纬度丢失起始结束位置计算时间条件
      /**
       * 计算采样周期,用于判断重量丢失的阈值
       * 取10组历史数据,取中位数作为数据采样的频率
       */
      let temFilterArr: any = []
      this.filterTimeDefault = 0
      if (len > 10) {
        for (let i = 0; i < 10; i++) {
          let time1 = this.changeTime(this.allData[i].uploadDate)
          let time2 = this.changeTime(this.allData[i + 1].uploadDate)
          let diffTime = (time2 - time1) / 1000
          temFilterArr.push(diffTime)
        }
        temFilterArr.sort(function (a, b) {
          return a - b
        })
        this.filterTimeDefault = Number(temFilterArr[6]) * 1.5
      }
      //			else {
      //				this.filterTimeDefault = (this.changeTime(this.allData[1].uploadDate) - this.changeTime(this.allData[0].uploadDate)) / 1000 * 1.5;
      //			}
      if (this.filterTime) {
        this.filterTimeDefault =
          Number(this.filterTime) > this.filterTimeDefault ? Number(this.filterTime) : this.filterTimeDefault
      }
      this.filterTimeDefault = this.filterTimeDefault > 150 ? this.filterTimeDefault : 150

      /**
       * 对筛选时间范围内,返回的历史数据做处理,对于数据缺失的时间段进行数据的补点,在echart对应显示灰色区域,表明该时间段范围内没有历史数据.
       */
      this.timeShadow = []
      if (common.mmsstoTimestamp(this.allData[0].uploadDate) - common.mmsstoTimestamp(this.startTime) > this.filterTimeDefault * 1000) {
        // 判断曲线数据前有没有过磅数据,有过磅数据,显示无数据区域,没有过磅数据则不显示无数据区域
        let hasWeightInEmptyDataStartTime: boolean = false
        for (let i = 0; i < this.loadometerData.length; i++) {
          let item = this.loadometerData[i]
          if (
            common.mmsstoTimestamp(this.startTime) < common.mmsstoTimestamp(item.date) &&
            common.mmsstoTimestamp(item.date) < common.mmsstoTimestamp(this.allData[0].uploadDate)
          ) {
            hasWeightInEmptyDataStartTime = true
            break
          }
        }
        if (hasWeightInEmptyDataStartTime) {
          let emptyDataStartTime = [] //存放搜索开始时间空数据补点的集合
          for (
            let t = common.mmsstoTimestamp(this.startTime);
            t < common.mmsstoTimestamp(this.allData[0].uploadDate);
            t = t + this.filterTimeDefault * 1000
          ) {
            let temDate = common.getTimeMmss(new Date(t))
            let temObj = {
              aCH1: '',
              aCH2: '',
              aCH3: '',
              aCH4: '',
              aCH5: '',
              aCH6: '',
              aCH7: '',
              aCH8: '',
              aCH9: '',
              aCH10: '',
              aCH11: '',
              aCH12: '',
              aCH13: '',
              aCH14: '',
              aCH15: '',
              aCH16: '',
              checkGps: '',
              checkWeight: '',
              deviceId: this.deviceId,
              handBrakeHardwareStatus: '',
              handBrakeSoftwareStatus: '',
              mWeight: '',
              rectifyWeight: '',
              rectifyX: '',
              rectifyY: '',
              speed: '',
              uploadDate: temDate,
              weight: '',
              x: this.allData[0].x,
              y: this.allData[0].y
            }
            emptyDataStartTime.push(temObj)
          }

          let emptyShadowStart = [
            {
              name: '无数据',
              xAxis: this.startTime
            },
            {
              xAxis: this.allData[0].uploadDate
            }
          ]
          this.timeShadow.push(emptyShadowStart)
          this.allData = emptyDataStartTime.concat(this.allData)
        }
      }
      if (common.mmsstoTimestamp(this.endTime) - common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) > this.filterTimeDefault * 1000) {
        // 判断曲线数据后有没有过磅数据,有过磅数据,显示无数据区域,没有过磅数据则不显示无数据区域
        let hasWeightInEmptyDataEndTime: boolean = false
        for (let i = 0; i < this.loadometerData.length; i++) {
          let item = this.loadometerData[i]
          if (
            common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) <
            common.mmsstoTimestamp(item.date) &&
            common.mmsstoTimestamp(item.date) < common.mmsstoTimestamp(this.endTime)
          ) {
            hasWeightInEmptyDataEndTime = true
            break
          }
        }
        if (hasWeightInEmptyDataEndTime) {
          let emptyDataEndTime = [] //存放搜索结束时间空数据补点的集合
          let EndTime: string
          if (new Date().getTime() - common.mmsstoTimestamp(this.endTime) > 0) {
            EndTime = this.endTime
          } else {
            EndTime = common.getNowTime()
          }
          for (
            let t =
              common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) + this.filterTimeDefault * 1000;
            t <= common.mmsstoTimestamp(EndTime);
            t = t + this.filterTimeDefault * 1000
          ) {
            let temDate = common.getTimeMmss(new Date(t))
            let temObj = {
              aCH1: '',
              aCH2: '',
              aCH3: '',
              aCH4: '',
              aCH5: '',
              aCH6: '',
              aCH7: '',
              aCH8: '',
              aCH9: '',
              aCH10: '',
              aCH11: '',
              aCH12: '',
              aCH13: '',
              aCH14: '',
              aCH15: '',
              aCH16: '',
              checkGps: '',
              checkWeight: '',
              deviceId: this.deviceId,
              handBrakeHardwareStatus: '',
              handBrakeSoftwareStatus: '',
              mWeight: '',
              rectifyWeight: '',
              rectifyX: '',
              rectifyY: '',
              speed: '',
              uploadDate: temDate,
              weight: '',
              x: this.allData[this.allData.length - 1].x,
              y: this.allData[this.allData.length - 1].y
            }
            emptyDataEndTime.push(temObj)
          }
          let emptyShadowEnd = [
            {
              name: '无数据',
              xAxis: this.allData[this.allData.length - 1].uploadDate
            },
            {
              xAxis: emptyDataEndTime[emptyDataEndTime.length - 1].uploadDate
            }
          ]
          this.timeShadow.push(emptyShadowEnd)
          this.allData = this.allData.concat(emptyDataEndTime)
        }
      }

      len = this.allData.length

      for (var i = 0; i < len; i++) {
        timeValue[i] = this.allData[i].uploadDate //x时间轴数据
        if (!this.allData[i].weight) {
          this.allData[i].weight = '-'
        }
        this.weightArr[i] = this.allData[i].weight //重量
        //				if (this.weightArr[i] < 0 && this.weightArr[i] >= -1){
        //					this.weightArr[i] = 0;
        //				}
        const _speed = parseFloat(this.allData[i].speed) //速度
        if (_speed > -1) {
          this.carSpeedArr[i] = parseFloat(this.allData[i].speed)
        } else {
          this.carSpeedArr[i] = 0
        }
        this.loadometerArr[i] = '-'
        nullGpsArr[i] = '-'
        //计算经纬度等于0.0或者丢失的时候是时长start
        if (!this.allData[i] || !this.allData[i].x || this.allData[i].x == '0.0') {
          loseLongLatArray.push(this.allData[i])
          if (isHavePoint === -1) {
            isHavePoint = i
          }
        } else {
          latestPointData = this.allData[i] // 每次都要记录正常的数据点
          if (isHavePoint !== -1) {
            var lostTime =
              (this.changeTime(this.allData[i].uploadDate) - this.changeTime(this.allData[isHavePoint].uploadDate)) /
              1000
            if (lostTime > this.filterTimeDefault) {
              var point = {
                value: this.convertTime(lostTime),
                xAxis: isHavePoint,
                yAxis: this.allData[isHavePoint].weight,
                lostime: lostTime
              }
              nullMarkerData.push(point)
            }
            isHavePoint = -1
          }
        }
        //计算end
        if (i < len - 2) {
          //获取丢失的数据
          let lostStartime = this.changeTime(this.allData[i].uploadDate)
          let lostEndtime = this.changeTime(this.allData[i + 1].uploadDate)
          let lostime = (lostEndtime - lostStartime) / 1000
          if (lostime > this.filterTimeDefault) {
            //重量时间段丢失
            var point = {
              value: this.convertTime(lostime),
              xAxis: i,
              yAxis: this.allData[i].weight,
              lostime: lostime
            }
            lostWeightMark.push(point)
          }
          if (!this.allData[i].x || this.allData[i].x == '0.0') {
            //经纬度坐标丢失
            if (i > 0) {
              isLostGps = true
              nullGpsArr[i] = this.allData[i].weight
            }
          }
        }
        var mapPoint = toMapPoint(this.allData[i])
        // if (
        //   mapPoint &&
        //   mapPoint.lng &&
        //   mapPoint.lat &&
        //   mapPoint.lng !== '0.0' &&
        //   mapPoint.lat !== '0.0' &&
        //   mapPoint.lat != '0' &&
        //   mapPoint.lng != '0'
        // ) {
        //   // this.linetoMapData[i] = this.allData[i]
        //   this.linetoMapData.push(this.allData[i])
        // }
        this.linetoMapData.push(this.allData[i])
        // 这里要考虑两种情况：
        // 1、从第一个点开始就没有经纬度，要一直记录到出现经纬度点然后赋值
        // 2、用前一个有经纬度的点覆盖后面所有没有经纬度的点
        if (loseLongLatArray.length > 0 && latestPointData) {
          for (var item of loseLongLatArray) {
            if (this.linetoMapData.includes(item)) {
              item.x = latestPointData.x
              item.y = latestPointData.y
              item.lat = latestPointData.lat
              item.lng = latestPointData.lng
            }
          }
          loseLongLatArray = []
        }
      }
      // 如果一个有效数据点都没有，则地图不用画线
      if (latestPointData == null) {
        this.linetoMapData = []
      }
      latestPointData = null

      //查询连续性为空的经纬度数据结束空的位置
      this.passageData = []
      //优化丢失的数据
      //			lostWeightMark=this.fillLosWeighttArr(lostWeightMark);
      //获取异常信息数据
      var self = this
      let alertReq = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime
      let logReq = 'deviceId=' + this.deviceId + '&startDate=' + this.startTime + '&endDate=' + this.endTime
      this.jsonApiService.http2('alertlog/queryAllTypeDeviceShutDownAlarmList.html', alertReq).subscribe(result => {
        this.jsonApiService.http2('log/queryLogByDeviceId.html', logReq).subscribe(data => {
          let alertArr = result.data
          let logArr = data.data
          let temResult = []
          if (alertArr.length > 0) {
            for (var i = 0; i < alertArr.length; i++) {
              alertArr[i].flag = 'alert'
            }
            temResult = temResult.concat(alertArr)
          }
          if (logArr.logForCoeList.length > 0) {
            for (var i = 0; i < logArr.logForCoeList.length; i++) {
              logArr.logForCoeList[i].flag = 'coef'
            }
            temResult = temResult.concat(logArr.logForCoeList)
          }
          if (logArr.UpgradeInfoList.length > 0) {
            for (var i = 0; i < logArr.UpgradeInfoList.length; i++) {
              logArr.UpgradeInfoList[i].flag = 'version'
            }
            temResult = temResult.concat(logArr.UpgradeInfoList)
          }
          //					this.powerOffAlertList = [];
          let len = temResult.length
          let offlineError = []
          if (len > 0) {
            for (let i = 0; i < len; i++) {
              let tim
              let sort = 0
              let item = temResult[i]
              let topos = toMapPoint({
                lng: item.lng,
                lat: item.lat
              })
              if (topos) {
                item.lng = topos.lng
                item.lat = topos.lat
              }
              if (item.flag == 'alert') {
                tim = this.changeTime(item.offTime)
              } else if (item.flag == 'coef') {
                tim = this.changeTime(item.sendTime)
              } else if (item.flag == 'version') {
                tim = this.changeTime(item.createTime)
              }
              for (let j = sort; j < this.allData.length; j++) {
                let _item = this.allData[j]
                let _tim = this.changeTime(_item.uploadDate)
                if (_tim - tim >= 0 && j > 0) {
                  sort = j
                  let errorItem: any
                  if (item.type == 1 && item.flag == 'alert') {
                    errorItem = {
                      name: '离线警报',
                      value: '离',
                      xAxis: j - 1,
                      yAxis: this.allData[j - 1].weight,
                      lostime: '',
                      rangeTime: item.totalSecond ? this.convertTime(item.totalSecond) : '离线中',
                      symbol: 'image://assets/img/trackImage/ofline_jb.png',
                      symbolSize: 24,
                      symbolOffset: ['0', '-50%']
                    }
                  } else if (item.type == 2 && item.flag == 'alert') {
                    errorItem = {
                      name: '断电警报',
                      value: '',
                      xAxis: j - 1,
                      yAxis: this.allData[j - 1].weight,
                      lostime: '',
                      rangeTime: item.totalSecond ? this.convertTime(item.totalSecond) : '断电中',
                      symbol: 'image://assets/img/trackImage/powerOff2.png',
                      symbolSize: 24,
                      symbolOffset: ['0', '-50%']
                    }
                    //										this.powerOffAlertList.push(item);//断电警报集合,处理echart显示断电区域使用
                  } else if (item.flag == 'coef') {
                    errorItem = {
                      name: '系数设置',
                      value: '系',
                      xAxis: j - 1,
                      yAxis: this.allData[j - 1].weight,
                      lostime: '',
                      symbol: 'image://assets/img/version_icon.png',
                      symbolSize: 26,
                      symbolOffset: ['0', '-50%']
                    }
                  } else if (item.flag == 'version') {
                    errorItem = {
                      name: '固件升级',
                      value: '固',
                      xAxis: j - 1,
                      yAxis: this.allData[j - 1].weight,
                      lostime: '',
                      symbol: 'image://assets/img/version_icon.png',
                      symbolSize: 26,
                      symbolOffset: ['0', '-50%']
                    }
                  }
                  if (errorItem) {
                    for (let keys in item) {
                      errorItem[keys] = item[keys]
                    }
                    offlineError.push(errorItem)
                  }
                  break
                }
              }
            }
          }
          /**
           *   处理警报不在历史数据时间范围之内,但在搜索的时间范围.  将不在历史数据时间范围的数据,补打在历史数据最后时间点上.
           */
          for (let w = 0; w < alertArr.length; w++) {
            let itemAlert = alertArr[w]
            if (
              this.changeTime(itemAlert.offTime) > this.changeTime(this.allData[this.allData.length - 1].uploadDate)
            ) {
              let errorItem: any
              let index = alertArr.length - w
              if (itemAlert.type == 1 && itemAlert.flag == 'alert') {
                errorItem = {
                  name: '离线警报',
                  value: '离',
                  xAxis: this.allData.length - index,
                  yAxis: this.allData[this.allData.length - index].weight,
                  lostime: '',
                  rangeTime: itemAlert.totalSecond ? this.convertTime(itemAlert.totalSecond) : '离线中',
                  symbol: 'image://assets/img/trackImage/ofline_jb.png',
                  symbolSize: 24,
                  symbolOffset: ['0', '-50%']
                }
              } else if (itemAlert.type == 2 && itemAlert.flag == 'alert') {
                errorItem = {
                  name: '断电警报',
                  value: '',
                  xAxis: this.allData.length - index,
                  yAxis: this.allData[this.allData.length - index].weight,
                  lostime: '',
                  rangeTime: itemAlert.totalSecond ? this.convertTime(itemAlert.totalSecond) : '断电中',
                  symbol: 'image://assets/img/trackImage/powerOff2.png',
                  symbolSize: 24,
                  symbolOffset: ['0', '-50%']
                }
              }
              if (errorItem) {
                for (let keys in itemAlert) {
                  errorItem[keys] = itemAlert[keys]
                }
                offlineError.push(errorItem)
              }
            }
          }
          for (let i = 0; i < offlineError.length; i++) {
            let item = offlineError[i]
            let isFind = false
            for (let _i = 0; _i < lostWeightMark.length; _i++) {
              let iem = lostWeightMark[_i]
              if (iem.flag) {
                if (item.xAxis == iem.xAxis) {
                  item.xAxis = item.xAxis + 1
                  item.lostime = iem.lostime
                  lostWeightMark.push(item)
                  isFind = true
                  break
                }
              } else {
                if ((item.xAxis < iem.xAxis + 1 && item.xAxis > iem.xAxis - 1) || item.xAxis == iem.xAxis) {
                  item.lostime = iem.lostime
                  lostWeightMark[_i] = item
                  isFind = true
                  break
                }
              }
            }
            if (!isFind) lostWeightMark.push(item)
          }
          this.passageData.push({
            name: '重量（吨）',
            type: 'line',
            borderWidth: 5,
            itemStyle: {
              color: '#c23531'
            },
            data: this.weightArr,
            markArea: {
              itemStyle: {
                color: '#ddd',
                opacity: 0.5
              },
              label: {
                color: '#333',
                fontSize: '16',
                position: ['50%', '50%'],
                offset: [-24, -8]
              },
              emphasis: {
                itemStyle: {
                  color: '#ddd',
                  opacity: 0.5
                },
                label: {
                  position: ['50%', '50%'],
                  offset: [-24, -8]
                }
              },
              data: this.timeShadow
            },
            markPoint: {
              data: lostWeightMark,
              itemStyle: {
                normal: {
                  label: {
                    fontSize: 10
                  }
                }
              }
            }
          })

          if (isLostGps) {
            this.passageData.push({
              name: '',
              type: 'line',
              itemStyle: {
                color: 'gray'
              },
              lineStyle: {
                width: 3 //折线宽度
              },
              data: nullGpsArr,
              markPoint: {
                data: nullMarkerData
              }
            })
          }
          //时间轴
          this.echartOption.xAxis.data = timeValue
          //ad信号
          this.showAdSignal()
          if (this.carSpeed) {
            this.yAxiSpeed.min = 0
            this.yAxiSpeed.max = 120
            this.showCarSpeed()
          }
          if (this.loadometer) {
            this.showLoadometer()
            //=============================================================红狮车辆:在厂区打点========================================================================
            // this.countPont('2') //显示在厂区
          }
          if (this.linetoMap) {
            this.showRailDeal()
          }

          this.yAxiSignal.show = this.lookSignal
          this.yAxiSpeed.show = this.carSpeed
          this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
          this.echartOption.series = this.passageData
          this.legendSleced['手刹信号'] = false
          this.echartOption.legend.selected = this.legendSleced
          this.jsonApiService
            .http2('realtime/getRealTimeDataForBase.html', 'deviceId=' + this.deviceId)
            .subscribe(result => {
              if (result.data.unit == '2') {
                this.echartOption.series[0].name = '重量（千克）'
              }
              this.myChart.setOption(this.echartOption, true)
              this.showMapTrack()
              this.voltageChange()
              this.offlineStatus && this.initOfflineData()
            })
        })
      })
    })

    setTimeout(() => {
      if (this.allData.length === 0 && this.isShowLoading) {
        this.isShowLoading = false
      }
    }, 60100)
  }
  //计算两个坐标点的距离
  GetDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = (lat1 * Math.PI) / 180.0
    var radLat2 = (lat2 * Math.PI) / 180.0
    var a = radLat1 - radLat2
    var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
    var s =
      2 *
      Math.asin(
        Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))
      )
    s = s * 6378.137 // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000
    return s
  }
  //厂区在线的经纬度点
  isJudgeHS: any = false //判断是不是红狮
  //计算是否厂区在线
  plantArea() {
    var that = this
    return new Promise(function (resolve, error) {
      that.jsonApiService
        .http2('realtime/getRealTimeDataForBase.html', 'deviceId=' + that.deviceId)
        .subscribe(result => {
          //判断是不是红狮
          that.jsonApiService
            .http2('company/isHongShiCar.html', 'companyId=' + result.data.companyId)
            .subscribe(result2 => {
              if (result2.success) {
                //判断是不是红狮
                if (result2.data == 1) {
                  that.isJudgeHS = true
                } else {
                  that.isJudgeHS = false
                }
              }
              resolve(null)
            })
        })
    })
  }
  // 处理红狮车辆  ,计算该车进入厂区的位置,标记在曲线图上
  countPont(type) {
    //isJudgeHS:true  查看车属于红狮的标识
    if (!this.isJudgeHS) return
    var that = this
    var len = that.allData && that.allData.length
    var pointWeightMark = [] //厂区内的点
    var isweightCount = false
    var pointObj

    for (var k = 0; k < that.passageData.length; k++) {
      if (that.passageData[k].name == '在厂区内') {
        that.passageData.splice(k, 1)
      }
    }
    // 绘制红狮围栏 [以公司经纬度为圆心,半径1000米],计算车辆轨迹是否经过围栏
    if (this.companyRailList.length > 0 && this.companyRailList.length > 0 && this.isJudgeHS) {
      let drivePathFirstPoint = { lng: this.allData[0].lng, lat: this.allData[0].lat }
      this.inTimeArr = []
      this.outTimeArr = []
      for (var r = 0; r < this.companyRailList.length; r++) {
        let distance = common.caculationDistance(drivePathFirstPoint, this.companyRailList[r].point)
        // 曲线点距离公司距离1000公里以上剔除,不用考虑监控是否进入围栏
        if (distance < 1000000) {
          this.getInOutTimeArr(0, this.companyRailList[r], this.companyDataList[r])
        }
      }
      // 对于进去围栏时间区间小于10分钟的情况剔除,不考虑是进入厂区,认为是路过[途径]围栏区域
      for (var i = 0; i < this.inTimeArr.length; i++) {
        let diffTime =
          common.mmsstoTimestamp(this.outTimeArr[i].endTime) - common.mmsstoTimestamp(this.inTimeArr[i].startTime)
        if (diffTime < 10 * 60 * 1000) {
          this.inTimeArr.splice(i, 1)
          this.outTimeArr.splice(i, 1)
          i = i - 1
        }
      }
    }
    //是否勾选地磅数据并且地磅是否有数据
    if (that.loadometer && that.loadometerData && that.loadometerData.length == 0) {
      if (len > 2) {
        var dataArray = []
        for (var i = 0; i < len; i++) {
          if (i < len - 2) {
            for (var w = 0; w < this.inTimeArr.length; w++) {
              // 只对进入围栏区域的点进行处理计算
              if (this.inTimeArr[w].index < i && i < this.outTimeArr[w].index) {
                let lostStartime1 = that.changeTime(that.allData[i].uploadDate)
                let lostEndtime1 = that.changeTime(that.allData[i + 1].uploadDate)
                var _weight = parseFloat(that.allData[i + 1].weight)
                //判断上货地点 且有重量存在
                if (
                  that.allData[i].weight == '0.0' &&
                  parseFloat(that.allData[i].weight) < _weight &&
                  lostStartime1 < lostEndtime1
                ) {
                  let n = 15
                  if (i + n < len - 13) {
                    let lostStartime = that.changeTime(that.allData[n].uploadDate)
                    let lostEndtime = that.changeTime(that.allData[n + 1].uploadDate)
                    if (lostStartime < lostEndtime) {
                      while (n < len - i - 13) {
                        n = n + 1
                        let pointweight = parseFloat(that.allData[i + n].weight)
                        let _weight1 = parseFloat(that.allData[i + n + 2].weight)
                        let _weight2 = parseFloat(that.allData[i + n + 4].weight)
                        let _weight3 = parseFloat(that.allData[i + n + 8].weight)
                        let _weight4 = parseFloat(that.allData[i + n + 12].weight)
                        let jssuanweight = (_weight1 + _weight2 + _weight3 + _weight4) / 4
                        if (Math.abs(jssuanweight - pointweight) < 1 && parseFloat(that.allData[i + n].speed) > 1) {
                          break
                        }
                      }
                    }
                  }
                  var startWeight = that.allData[i].weight
                  var startUploadDate = that.allData[i].uploadDate
                  var startLeaveTime = that.allData[i + n].uploadDate
                  pointObj = {
                    name: '在厂区内',
                    value: '',
                    xAxis: i - 1,
                    yAxis: startWeight,
                    lostime: this.inTimeArr[w].startTime,
                    companyName: this.inTimeArr[w].companyName,
                    symbol: 'image://assets/img/trackImage/company.png',
                    symbolSize: [34, 44],
                    symbolOffset: ['0', '-50%'],
                    carNumber: that.carNumber,
                    leaveTime: this.outTimeArr[w].endTime
                  }
                  pointWeightMark.push(pointObj)
                }
              }
            }
          }
        }
        //计算没有上货点的情况下,进入厂区围栏的情况
        let otherPoint: any = [],
          aver: number,
          isFind: boolean = false
        for (var w = 0; w < this.inTimeArr.length; w++) {
          isFind = false
          for (let j = 0; j < pointWeightMark.length; j++) {
            if (
              this.inTimeArr[w].index < pointWeightMark[j].xAxis &&
              pointWeightMark[j].xAxis < this.outTimeArr[w].index
            ) {
              isFind = true
              continue
            }
          }
          if (!isFind) {
            aver = Math.floor((this.inTimeArr[w].index + this.outTimeArr[w].index) / 2) //取进入围栏和出围栏中间点作为在厂区标识
            if (!otherPoint.includes(aver)) {
              let pointObj = {
                name: '在厂区内',
                value: '',
                xAxis: aver - 1,
                yAxis: '0.0',
                companyName: this.inTimeArr[w].companyName,
                lostime: this.inTimeArr[w].startTime,
                symbol: 'image://assets/img/trackImage/company.png',
                symbolSize: [34, 44],
                symbolOffset: ['0', '-50%'],
                carNumber: that.carNumber,
                leaveTime: this.outTimeArr[w].endTime
              }
              otherPoint.push(aver)
              pointWeightMark.push(pointObj)
            }
          }
        }
        this.passageData.push({
          name: '在厂区内',
          type: 'line',
          borderWidth: 0,
          itemStyle: {
            color: '#37a2da'
          },
          lineStyle: {
            width: 1
          },
          markPoint: {
            data: pointWeightMark
          }
        })
        this.echartOption.series = this.passageData
      }
    } else {
      let lens = that.passageData.length
      for (var i = 0; i < lens; i++) {
        if (that.passageData[i].name === '在厂区内') {
          that.passageData.splice(i, 1)
          break
        }
      }
      that.echartOption.series = that.passageData
      if (type == '1') {
        that.myChart.setOption(that.echartOption, true)
      }
    }
  }
  // 获取公司经纬度,绘制围栏,如果是红狮车辆,则计算是否进入围栏[厂区]
  companyRailList: any = [] //公司围栏
  companyDataList: any = [] //公司数据
  getCompanyRail() {
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    this.jsonApiService.http2('company/queryLowestLevelCompany.html', 'deviceId=' + this.deviceId).subscribe(result => {
      if (result.data && result.data.length > 0) {
        //	            this.myMap.clearOverlays();
        if (this.companyRailList.length > 0) {
          for (let item of this.companyRailList) {
            this.myMap.removeOverlay(item)
          }
        }
        this.companyRailList = []
        this.companyDataList = []
        let companyList = result.data
        for (let item of companyList) {
          let mapPoint = toMapPoint({ lng: item.lng, lat: item.lat })
          if (item.lng && item.lat) {
            this.companyDataList.push(item)
            let point = new BMap.Point(mapPoint.lng, mapPoint.lat) //红狮公司经纬度数据坐标为百度坐标系
            let circle = new BMap.Circle(point, 1000, railStyle) //创建圆
            this.companyRailList.push(circle)
            this.myMap.addOverlay(circle)
          }
        }
      }
    })
  }

  showRailChange() {
    if (this.carSpeedArr.length >= 1) {
      if (this.linetoMap) {
        this.showRailDeal()
      } else {
        let len = this.passageData.length
        for (var i = 0; i < len; i++) {
          if (this.passageData[i].name === '围栏') {
            this.passageData.splice(i, 1)
            break
          }
        }
      }
      this.echartOption.series = this.passageData
      this.myChart.setOption(this.echartOption, true)
    }
  }

  showRailDeal() {
    var area = []
    for (var i = 0; i < this.inTimeArr.length; i++) {
      var dataArr = [
        {
          name: this.inTimeArr[i].companyName,
          xAxis: this.inTimeArr[i].startTime
        },
        {
          xAxis: this.outTimeArr[i].endTime
        }]
      area.push(dataArr)
    }

    this.passageData.push({
      name: '围栏',
      type: 'line',
      smooth: true,
      // data: this.carSpeedArr,
      markArea: {
        data: area,
      }
    })
    this.echartOption.series = this.passageData
    this.myChart.setOption(this.echartOption, true)
  }

  drawRailDeal() {
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    this.inTimeArr = [];
    this.outTimeArr = [];
    this.jsonApiService.http2('company/queryLowestLevelCompany.html', 'deviceId=' + this.deviceId).subscribe(result => {
      if (result.data && result.data.length > 0) {
        let companyList = result.data
        for (let item of companyList) {
          let mapPoint = toMapPoint({ lng: item.lng, lat: item.lat })
          if (mapPoint) {
            let point = new BMap.Point(mapPoint.lng, mapPoint.lat)
            let circle = new BMap.Circle(point, item.radius, railStyle)
            this.myMap.addOverlay(circle)
            this.getInOutTimeArr(0, circle, item)
          }
        }
      }
    })
  }

  //getInOutTimeArr：计算进入跟离开行政区的时间点
  inTimeArr: any = [] //记录进入围栏的时间
  outTimeArr: any = [] //记录离开围栏的时间
  inCompantList: any = [] //记录进入厂区,离开厂区的数据
  getInOutTimeArr(order, chartAreaPly, companyData) {
    let trackData = this.allData
    var isOut = false //判断是否再进入边界后又再次出去
    var len = trackData.length
    for (var i = order; i < len; i++) {
      let pointToMapIn = toMapPoint({ lng: trackData[i].x, lat: trackData[i].y });//大地转百度坐标系
      var comparePoint = new BMap.Point(pointToMapIn.lng, pointToMapIn.lat);
      var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, chartAreaPly)
      if (result) {
        //在内部，把该点显示在地图上
        this.inTimeArr.push({ startTime: trackData[i].uploadDate, index: i, companyName: companyData.companyName })
        for (var j = i; j < len; j++) {
          let pointToMapOut = toMapPoint({ lng: trackData[j].x, lat: trackData[j].y });//大地转百度坐标系
          var comparePoint = new BMap.Point(pointToMapOut.lng, pointToMapOut.lat);
          var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, chartAreaPly)
          if (!result) {
            //在内部，把该点显示在地图上
            isOut = true //判断是否再进入边界后又再次出去
            this.outTimeArr.push({ endTime: trackData[j].uploadDate, index: j, companyName: companyData.companyName })
            if (j < len) {
              this.getInOutTimeArr(j, chartAreaPly, companyData)
            }
            break
          }
        }
        if (!isOut) {
          this.outTimeArr.push({
            endTime: trackData[len - 1].uploadDate,
            index: len - 1,
            companyName: companyData.companyName
          })
        }
        break
      }
    }
  }

  fillLosWeighttArr(paramArr) {
    let result = []
    let len = paramArr.length
    if (len > 30) {
      let eq = Math.floor(this.allData.length / 100)
      let multiple = 1.5 //倍数
      for (let i = 0; i < len - 1; i++) {
        let item1 = paramArr[i]
        let item2 = paramArr[i + 1]
        if (i < 1) {
          result.push(item1)
        } else {
          let sort = item2.xAxis - item1.xAxis
          if (sort > eq || item2.lostime > item1.lostime * multiple || item2.lostime < item1.lostime / multiple) {
            result.push(item1)
          }
        }
      }
      if (len > 1) {
        let lastItem = paramArr[len - 1]
        result.push(lastItem)
      }
    } else {
      result = paramArr
    }
    return result
  }

  //绘画车辆速度折线
  showCarSpeed() {
    let obj = {
      name: '车辆速度',
      type: 'line',
      yAxisIndex: 2,
      itemStyle: {
        normal: {
          color: '#5793f3',
          lineStyle: {
            width: 1, //折线宽度
            opacity: 0.5
          }
        }
      },
      data: this.carSpeedArr,
      areaStyle: {
        color: 'rgba(83, 146, 230,0.5)'
      }
    }
    this.passageData.push(obj)
  }

  //绘画ad信号折线,及丢失数据点.
  showAdSignal() {
    this.passageName = []
    this.passageArr = []
    var data = this.allData
    var len = data.length
    let wareStatusArr = [] //手刹信号
    //nullPassArr中对应的值为空的时候,从allPassArr移除对应的通道数据,最终得到filterArr过滤后的数据this.passageArr
    var allPassArr = [] //16通道所有的数组
    var nullPassArr = [] //记录通道全部数据是否为空.,默认值为true
    for (var z = 0; z < 16; z++) {
      var newArr = new Array()
      allPassArr.push(newArr)
      nullPassArr.push(true)
    }
    for (var i = 0; i < len; i++) {
      var handSingal = parseFloat(data[i].handBrakeHardwareStatus) * 10 * this.multiple //手刹信号放大10万倍
      if (handSingal >= 0 || handSingal < 0) {
        wareStatusArr[i] = handSingal
      }
      for (var j = 0; j < 16; j++) {
        var name = 'aCH' + (j + 1)
        var passVal = parseFloat(data[i][name]) //获取16个通道的值;
        allPassArr[j][i] = passVal
        if (passVal > 0 || passVal < 0) {
          nullPassArr[j] = false
        }
      }
    }

    this.legendSleced = {}

    const sensorNameArr = this.sensorModuleList.map(item => '通道' + item.value)
    const sensorIncludeCoefName = this.sensorModuleList.filter(item => item.flag).map(item => '通道' + item.value)

    for (var _z = 0; _z < nullPassArr.length; _z++) {
      if (!nullPassArr[_z]) {
        var passName = '通道' + (_z + 1)
        this.passageName.push(passName)
        //通道16切换数据
        // if(_z == 15){
        // 	for(let i16=0;i16< allPassArr[_z].length;i16++){
        // 		if(allPassArr[_z][i16] == 'NaN' || allPassArr[_z][i16] == NaN || isNaN(allPassArr[_z][i16])){
        // 			allPassArr[_z][i16] = ""
        // 		}
        // 	}
        // }
        this.passageArr.push(allPassArr[_z])
        // 如果是环卫车类型，则根据传感器序号显示对应的通道号
        if (this.deviceBaseInfo.useTypeL1 === '02') {
          this.legendSleced[passName] = sensorNameArr.includes(passName)
        } else {
          this.legendSleced[passName] = sensorIncludeCoefName.includes(passName)
          // if (this.hideOrshowline.indexOf(passName) > -1) {
          //   this.legendSleced[passName] = true
          // } else {
          //   this.legendSleced[passName] = false
          // }
        }
      }
    }
    if (!nullPassArr[15]) {
      // 当16通道的值不为空时候
      this.signal16Arr = allPassArr[15]
      this.isRate16 = true
    } else {
      this.isRate16 = false
    }
    if (wareStatusArr.length > 1) {
      this.passageName.push('手刹信号')
      this.passageArr.push(wareStatusArr)
    }

    if (this.lookSignal) {
      for (var _i = 0; _i < this.passageName.length; _i++) {
        var obj = {
          name: this.passageName[_i],
          type: 'line',
          yAxisIndex: 1,
          itemStyle: {
            color: common.lineGetColor(_i)
          },
          lineStyle: {
            width: 2, //折线宽度
            opacity: 0.75
          },
          data: this.passageArr[_i]
        }
        if (this.passageName[_i] === '手刹信号') {
          obj.itemStyle = {
            color: '#8B668B'
          }
          obj.yAxisIndex = 0
        }
        //通道16切换数据
        // if (this.passageName[_i] == "通道16") {
        // 	obj.type = 'scatter';
        // 	obj.yAxisIndex = 0;
        // 	obj.itemStyle = {
        // 		color: 'orange'
        // 	}
        // 	console.log(this.passageArr[_i])
        // }
        this.passageData.push(obj)
      }
    }
  }

  offlineShowData = {
    offTime: '',
    onTime: '',
    totalSecond: 0,
    showDate: '',
    lacForOffline: '',
    cellidForOffline: '',
    rssiForOffline: '',
    baseInfoBefore: '-',
    lacForOnline: '',
    cellidForOnline: '',
    rssiForOnline: '',
    baseInfoAfter: '-',
  }
  //地图联动绘画轨迹路线.
  showMapTrack() {
    if (!this.linetoMapData || this.linetoMapData.length === 0) {
      return
    }
    let pointArr = this.linetoMapData
    let map = this.myMap
    //绘制路线

    var geturl = config.BaseURL
    let lineStyle = { star: true, end: false, color: true, infoUrl: geturl }
    drawTrackLine(pointArr, map, lineStyle)
    setTimeout(function () {
      map.centerAndZoom(new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat), 12)
    }, 10)
    let that = this
    let promptBox = $('.weightPromptBox')
    let alertPromptBox = $('.alertPromptBox')
    let versionChartModuleBox = $('.versionChartModuleBox')
    let coefChartModuleBox = $('.coefChartModuleBox')
    let companyChartModuleBox = $('.companyChartModuleBox')
    const offlineBox = $('.offlinePromptBox')

    this.myChart.on('mouseout', function () {
      promptBox.hide()
      offlineBox.hide()
      alertPromptBox.hide()
      versionChartModuleBox.hide()
      coefChartModuleBox.hide()
      companyChartModuleBox.hide()
    })
    var options = {
      size: 7,
      shape: 3,
      color: 'rgba(0, 0, 0, 0)'
    }
    this.myChart.on('mousemove', function (params, event) {
      if (that.isMoveFlag) {
        that.isMoveFlag = false
        if (params.seriesType === 'scatter') {
          // 点击地磅数据的点
          var e = event || window.event
          var x1 = $('#content').offset().left
          var y1 = $('#content').offset().top
          if (params.seriesName === '地磅数据') {
            var x = e.clientX - x1 - 20 - promptBox.width()
            var y = e.clientY - y1 - 20 - promptBox.height()
            that.poundWeight = params.data //当前地磅重量
            that.errorValue = common.twoDecimal(that.allData[params.dataIndex].weight * that.multiple - params.data) //重量误差值
            if (params.data == 0) {
              that.errorRate = ''
            } else {
              that.errorRate = common.twoDecimal(Math.abs(that.errorValue / params.data) * 100) //重量误差率
            }
            if (that.isRate16) {
              that.ad16Value = common.twoDecimal(that.signal16Arr[params.dataIndex] * that.multiple - params.data) //16通道信号误差值
              if (that.ad16Value == 0) {
                that.ad16Rate = 0
              } else {
                if (params.data == 0) {
                  that.ad16Rate = ''
                } else {
                  that.ad16Rate = common.twoDecimal(Math.abs(that.ad16Value / params.data) * 100) //16通道信号误差率
                }
              }
            }
            promptBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          } else if (params.seriesName === '网络离线') {
            that.offlineShowData = params.data.data
            that.offlineShowData.showDate = that.convertTime(that.offlineShowData.totalSecond || 0)
            that.offlineShowData.baseInfoBefore = !that.offlineShowData.lacForOffline && !that.offlineShowData.cellidForOffline && !that.offlineShowData.rssiForOffline
              ? '-' :
              (that.offlineShowData.lacForOffline || '-') + ', ' + (that.offlineShowData.cellidForOffline || '-') + ', ' +
              (that.offlineShowData.rssiForOffline || '-')


            that.offlineShowData.baseInfoAfter = !that.offlineShowData.lacForOnline && !that.offlineShowData.cellidForOnline && !that.offlineShowData.rssiForOnline
              ? '-' :
              (that.offlineShowData.lacForOnline || '-') + ', ' + (that.offlineShowData.cellidForOnline || '-') + ', ' +
              (that.offlineShowData.rssiForOnline || '-')

            const x = e.clientX - x1 - 20 - 270
            const y = e.clientY - y1 - 20 - 132
            offlineBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          }
        } else {
          promptBox.hide()
          offlineBox.hide()
        }
        if (params.componentType === 'markPoint') {
          if (params.name == '离线警报' || params.name == '断电警报') {
            params.data.onTime = params.data.onTime ? params.data.onTime : '无'
            that.alertChartModelInfo = params.data
            var e = event || window.event
            var x = e.offsetX - 272
            var y = e.offsetY - 32 > 260 ? e.offsetY - 32 : e.offsetY - 120
            alertPromptBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          }
          if (params.name == '固件升级') {
            that.versionChartModuleInfo = params.data
            var e = event || window.event
            var x = e.offsetX - 384
            var y = e.offsetY - 32 > 260 ? e.offsetY - 32 : e.offsetY - 80
            versionChartModuleBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          }

          if (params.name == '系数设置') {
            that.coefChartModuleInfo = params.data
            var e = event || window.event
            var x = e.offsetX - 324
            var y = e.offsetY - 32 > 260 ? e.offsetY - 32 : e.offsetY - 80
            coefChartModuleBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          }

          if (params.name == '在厂区内') {
            that.companyChartModuleInfo = params.data
            var e = event || window.event
            var x = e.offsetX - 250
            var y = e.offsetY - 10
            companyChartModuleBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          }
        }
        that.myMap.closeInfoWindow() //关闭信息窗口
        setTimeout(() => {
          that.isMoveFlag = true
        }, 80)
      }
    })
  }
  //折线移动,地图轨迹添加坐标位置点函数
  lineMoveCarPoint(data) {
    if (data.lat > 0) {
      var mp = this.myMap
      var update = function update() {
        var ctx = this.canvas.getContext('2d')
        if (!ctx) {
          return
        }
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
        var point = new BMap.Point(data.lng, data.lat)
        var pixel = mp.pointToPixel(point)
        ctx.beginPath()
        ctx.strokeStyle = '#d0d4d7'
        ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI)
        ctx.stroke()
        ctx.beginPath()
        ctx.fillStyle = 'rgba(35, 152, 255, 0.14)'
        ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI)
        ctx.fill()
        ctx.beginPath()
        ctx.strokeStyle = '#c2c2c4'
        ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI)
        ctx.stroke()
        ctx.beginPath()
        ctx.fillStyle = '#fff'
        ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI)
        ctx.fill()
        ctx.beginPath()
        ctx.fillStyle = '#1496ff'
        ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI)
        ctx.fill()
      }
      if (typeof this.carMoveCanvasLayer != 'undefined') {
        this.carMoveCanvasLayer.options.update = update
        this.carMoveCanvasLayer._draw()
        return
      }
      this.carMoveCanvasLayer = new CanvasLayer({
        map: this.myMap,
        update: update,
        zIndex: 10
      })
    }
  }
  //地磅数据赋值到对应的折线数据位置上,若数据上有值则往后移
  loadometerVoluation(sort, weight) {
    if (sort + 1 <= this.loadometerArr.length) {
      if (this.loadometerArr[sort + 1] == '-') {
        this.loadometerArr[sort + 1] = weight
      } else {
        this.loadometerVoluation(sort + 1, weight)
      }
    }
  }
  //获取地磅数据在chart图表显示.
  showLoadometer() {
    var orderIndex = 0
    for (var x = 0; x < this.loadometerData.length; x++) {
      var time1 = common.mmsstoTimestamp(this.loadometerData[x].date)
      for (var i = orderIndex; i < this.allData.length; i++) {
        var time2 = common.mmsstoTimestamp(this.allData[i].uploadDate)
        orderIndex++
        if (time2 - time1 >= 0) {
          let lmWeight = parseFloat(this.loadometerData[x].weight)
          this.loadometerVoluation(i - 1, lmWeight)
          break
        }
      }
    }
    if (this.loadometerData.length >= 1) {
      let obj = {
        name: '地磅数据',
        type: 'scatter',
        yAxisIndex: 0,
        itemStyle: {
          color: 'orange'
        },
        data: this.loadometerArr
      }
      this.passageData.push(obj)
    }
  }

  //ad信号选中画信号折线
  signalChange() {
    let len = this.passageArr.length
    if (len >= 1) {
      if (this.lookSignal) {
        for (var i = 0; i < len; i++) {
          //添加传感器通道数据
          var obj = {
            name: this.passageName[i],
            type: 'line',
            yAxisIndex: 1,
            itemStyle: {
              color: common.lineGetColor(i)
            },
            lineStyle: {
              width: 2, //折线宽度
              opacity: 0.75
            },
            data: this.passageArr[i]
          }
          if (this.passageName[i] === '手刹信号') {
            obj.itemStyle = {
              color: '#8B668B'
            }
            obj.yAxisIndex = 0
          }
          this.passageData.push(obj)
        }
      } else {
        var _len = this.passageData.length

        for (var _i = 0; _i < _len; _i++) {
          let findIndex = this.passageName.indexOf(this.passageData[_i].name)
          if (findIndex > -1) {
            this.passageData.splice(_i, 1)
            _len = _len - 1
            _i = _i - 1
          }
        }
      }
      this.yAxiSignal.show = this.lookSignal
      this.yAxiSpeed.show = this.carSpeed
      this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
      this.echartOption.series = this.passageData
      this.myChart.setOption(this.echartOption, true)
    }
  }
  //地磅数据选中画折线
  loadometerChange() {
    if (!this.carNumber) {
      //无车牌号则清空设备id
      this.deviceId = ''
    }
    //拉取磅单数量
    if (this.selectedCompanyId) {
      this.queryCarListByCompanyId()
    }
    if (this.allData.length < 2) {
      return
    }

    if (this.loadometerData.length >= 1) {
      if (this.loadometer) {
        this.showLoadometer()
      } else {
        let len = this.passageData.length
        for (var i = 0; i < len; i++) {
          if (this.passageData[i].name === '地磅数据') {
            this.passageData.splice(i, 1)
            break
          }
        }
      }
      this.echartOption.series = this.passageData
    } else {
      // this.countPont('1')
      if (this.loadometer) {
        this.message('该时间段没有地磅数据')
      }
    }
    this.myChart.setOption(this.echartOption, true)
  }
  //车辆速度选中画折线
  carSpeedChange() {
    if (this.carSpeedArr.length >= 1) {
      if (this.carSpeed) {
        this.yAxiSpeed.min = 0
        this.yAxiSpeed.max = 120
        this.showCarSpeed()
      } else {
        this.yAxiSpeed.min = undefined
        this.yAxiSpeed.max = undefined
        let len = this.passageData.length
        for (var i = 0; i < len; i++) {
          if (this.passageData[i].name === '车辆速度') {
            this.passageData.splice(i, 1)
            break
          }
        }
      }
      this.yAxiSignal.show = this.lookSignal
      this.yAxiSpeed.show = this.carSpeed
      this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
      this.echartOption.series = this.passageData
      this.myChart.setOption(this.echartOption, true)
    }
  }
  //修正数据选中画折线
  modifyChange() {
    if (this.allData.length < 1) {
      return
    }
    this.askForData()
  }

  /**
 * 网络离线位置切换显示
 */
  offlineStatus = false
  // 保存网络离线位置数据，如果没有点击数据绘图，只是切换显示，无需绘制
  offlineData = []
  offlineMarkers = {
    name: '网络离线',
    type: 'scatter',
    yAxisIndex: 0,
    symbol: 'image://assets/img/trackImage/base.png',
    symbolSize: 24,
    symbolOffset: ['0', '-50%'],
    // itemStyle: {
    //   color: 'red'
    // },
    data: []
  }
  offlineStatusChange(e) {
    // 还未开始绘制，不用请求
    if (this.allData.length < 1) {
      return
    }
    const isSelected = e.target.checked
    // 取消选中清空数据，移除标记
    if (!isSelected) {
      this.offlineData = []
      // 删除网络离线
      if (this.passageData.includes(this.offlineMarkers)) {
        this.passageData.splice(this.passageData.findIndex(item => item === this.offlineMarkers), 1)
        this.echartOption.series = this.passageData
        // 刷新 echart
        this.myChart.setOption(this.echartOption, true)
      }
      return
    }
    if (this.deviceId == '') {
      this.message('请选择需要查看的车辆')
      return
    }
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()
    if (this.startTime == '') {
      this.message('开始时间不能为空')
      return
    }
    if (this.endTime == '') {
      this.message('结束时间不能为空')
      return
    }

    if (isSelected) {
      this.initOfflineData()
    }
  }

  initOfflineData() {
    this.jsonApiService.http_obj('stats/getNetworkOffline.html', {
      deviceId: this.deviceId,
      startTime: this.startTime,
      endTime: this.endTime,
      filter: this.filterTimeDefault
    }).subscribe(result => {
      this.offlineData = result.data
      this.showOfflineMarkers()
    })
  }

  //获取地磅数据在chart图表显示.
  showOfflineMarkers() {
    if (this.offlineData.length === 0) return
    let index = 0 // 查找对应横轴坐标
    const data = []
    for (let x = 0; x < this.offlineData.length; x++) {
      const time1 = common.mmsstoTimestamp(this.offlineData[x].uploadDate)
      for (let i = index; i < this.allData.length; i++) {
        const time2 = common.mmsstoTimestamp(this.allData[i].uploadDate)
        index++
        // 第一个超过的位置，去上一个位置做坐标
        if (time2 - time1 >= 0) {
          data[i] = { value: this.allData[i].weight, data: this.offlineData[x] }
          break
        }
      }
    }
    this.offlineMarkers.data = data
    this.passageData.push(this.offlineMarkers)
    this.echartOption.series = this.passageData
    // 刷新 echart
    this.myChart.setOption(this.echartOption, true)
  }

  //选中需要输入框获取折线图上的时间,添加endueTime类事件
  inpSelectEvent(val) {
    this.inpSelect = val
  }

  //转换时间格式
  convertTime(timeInt) {
    var d, h, m, s
    if (timeInt >= 0) {
      d = Math.floor(timeInt / 60 / 60 / 24)
      h = Math.floor((timeInt / 60 / 60) % 24)
      m = Math.floor((timeInt / 60) % 60)
      s = Math.floor(timeInt % 60)
    }
    if (d < 1) {
      if (h < 1) {
        // 	 return m+'分'+s+'秒';
        return '约' + m + '分'
      } else {
        return h + '小时' + m + '分'
      }
    } else {
      return d + '天' + h + '小时' + m + '分'
    }
  }
  openConfigView(modal) {
    if (!this.deviceId) {
      this.jsonApiService.message('未选择车辆')
      return
    }
    modal.show()
    this.coefCarNumber = $('#select2-carNumberSelect2-container').attr('title')
    this.getConfigParams()
  }
  closeConfigView(modal) {
    modal.hide()
  }

  initCoefficientList() {
    this.coefficientList = []
    for (let i = 0; i < 16; i++) {
      let obj = {
        coef: '',
        index: i + 1
      }
      this.coefficientList.push(obj)
    }
  }

  getConfigParams() {
    let reqdata = 'deviceId=' + this.deviceId
    this.jsonApiService.http('realtime/getRealTimeData.html', reqdata).subscribe(result => {
      if (!result.data.coef) return
      if (result.data.runStatus !== '0') this.coefCarStatus = 'online'
      for (let i = 0; i < result.data.coef.length; i++) {
        this.coefficientList[i].coef = result.data.coef[i]
      }
    })
  }
  submitConfigMapped(modal) {
    modal.show()
    let params = {
      protocolVersion: '2',
      online: this.coefCarStatus,
      deviceId: this.deviceId
    }
    for (let item of this.coefficientList) {
      let keys = 'channel' + item.index
      params[keys] = item.coef
    }
    let reqdata = ''
    for (let keys in params) {
      reqdata = reqdata + keys + '=' + params[keys] + '&'
    }
    reqdata = reqdata.substring(0, reqdata.length - 1)
    this.jsonApiService.http2('system/remotetuning.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
    })
  }
  startTime_problem: string = ''
  endTime_problem: string = ''
  isPush = '0'
  initProTypeOptions() {
    this.proTypeOptions = problemOptions.initProTypeOptions
  }
  //监听问题类型改变事件
  problemTypeChange() {
    if (this.proTypeParams.problemType == '') return
    let sort = +this.proTypeParams.problemType
    this.proSlectedItem = this.proTypeOptions[sort]
    this.proTypeParams.problemClass = ''
    this.problemClassChange()
  }
  //监听问题分类改变事件
  pcIsOther = false
  otherInpMess = ''
  problemClassChange() {
    this.seneorPhenlist = []
    this.proTypeParams.phenomenon = ''
    this.otherInpMess = ''
    this.isPush = '0'
    //		判断选的是不是其他
    let isOther = this.proSlectedItem.childs[+this.proTypeParams.problemClass].name
    if (isOther == '其他') {
      this.pcIsOther = true
    } else {
      this.pcIsOther = false
    }
    if (this.proTypeParams.problemType == '1' && this.proTypeParams.problemClass == '1') {
    } else {
      this.problemPhenChange()
    }
  }
  //监听问题现象改变事件
  problemPhenChange() {
    this.proTypeParams.repairGuide = ''
    this.proTypeParams.repairWay = ''
    this.proTypeParams.pheDescribe = ''
  }
  addseneorPhenItem() {
    let sensor = $('#sensorPhenName').val()
    if (!sensor || !this.proTypeParams.phenomenon) {
      this.jsonApiService.message('请选择传感器问题现象')
      return
    }
    let len = this.seneorPhenlist.length
    let itemId = 1
    if (len > 0) {
      itemId = this.seneorPhenlist[len - 1].index + 1
    }

    let phen =
      this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name
    let isAdd = true
    for (let item of this.seneorPhenlist) {
      if (item.phenomenon == phen) {
        let str = '传感器' + sensor
        if (str == item.sensorName) {
          isAdd = false
          break
        }
      }
    }
    if (isAdd) {
      let pheItem = {
        index: itemId,
        sensorName: '传感器' + sensor,
        phenomenon: phen
      }
      this.seneorPhenlist.push(pheItem)
    } else {
      this.jsonApiService.message('现象已存在,不需要重复添加')
    }
  }
  delSeneorPhenItem(index) {
    this.jsonApiService.confirm_message('确定删除该条现象?').then(() => {
      this.seneorPhenlist.splice(index, 1)
    })
  }

  getSelectedVAL() {
    var result: any = {
      problemTypeStr: this.proSlectedItem.name, //问题类型
      problemClassStr: '',
      phenomenonStr: '',
      repairGuideStr: '',
      repairWayStr: '',
      pheDescribeStr: '',
      resultPhenStr: ''
    }
    if (!this.proSlectedItem) {
      this.jsonApiService.message('请选择问题类型')
      return result
    }
    if (this.proTypeParams.problemClass) {
      //问题分类
      result.problemClassStr = this.proSlectedItem.childs[+this.proTypeParams.problemClass].name
    }
    if (this.proTypeParams.phenomenon) {
      //问题现象
      result.phenomenonStr =
        this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name
      result.resultPhenStr = result.phenomenonStr
    }
    if (this.proTypeParams.repairGuide) {
      //维修指导
      result.repairGuideStr =
        this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[
          +this.proTypeParams.phenomenon
        ].repairGuide[+this.proTypeParams.repairGuide].name
    }
    if (this.proTypeParams.repairWay) {
      //维修方式
      result.repairWayStr =
        this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[
          +this.proTypeParams.phenomenon
        ].repairWay[+this.proTypeParams.repairWay].name
    }
    if (this.proTypeParams.pheDescribe) {
      //维修描述
      result.pheDescribeStr =
        this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[
          +this.proTypeParams.phenomenon
        ].pheDescribe[+this.proTypeParams.pheDescribe].name
    }

    if (this.seneorPhenlist.length > 0) {
      let list = []
      for (let item of this.seneorPhenlist) {
        let str = item.sensorName + '-' + item.phenomenon
        list.push(str)
      }
      result.resultPhenStr = list.join(',')
    }
    if (this.pcIsOther) {
      result.resultPhenStr = this.otherInpMess
    }
    return result
  }

  submitRecord() {
    if (!this.deviceId) {
      this.jsonApiService.message('先选择车辆...')
      return
    }
    if (!this.proTypeParams.problemType) {
      this.jsonApiService.message('请选择问题分类')
      return
    }
    if (!this.startTime_problem || !this.endTime_problem) {
      this.jsonApiService.message('问题起始时间不能为空...')
      return
    }
    let timeCheck = common.correctTimeParams(this.startTime_problem, this.endTime_problem, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let operaParam = this.getSelectedVAL()
    if (this.proTypeParams.problemType == '1' && this.proTypeParams.problemClass == '1') {
      let sensor = $('#sensorPhenName').val()
      if (this.seneorPhenlist.length < 1 && !sensor && !this.proTypeParams.phenomenon) {
        this.jsonApiService.message('请确认添加传感器问题现象')
        return
      }
      if (sensor && this.proTypeParams.phenomenon) {
        let phen =
          this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name
        let phenResult = '传感器' + sensor + '-' + phen
        if (this.seneorPhenlist.length < 1) {
          operaParam.resultPhenStr = phenResult
        } else {
          let findIndex = operaParam.resultPhenStr.indexOf(phenResult)
          if (findIndex < 0) {
            operaParam.resultPhenStr = operaParam.resultPhenStr + ',' + phenResult
          }
        }
      }
    }
    if (!this.proTypeParams.problemType || !this.proTypeParams.problemClass) {
      this.jsonApiService.message('请选择问题分类')
      return
    }
    if (operaParam.resultPhenStr == '') {
      this.jsonApiService.message('问题现象不能为空')
      return
    }
    let proType = +this.proTypeParams.problemType + 1 + '0' + (+this.proTypeParams.problemClass + 1)
    if (operaParam.problemClassStr == '其他') {
      proType = +this.proTypeParams.problemType + 1 + '00'
    }
    this.jsonApiService.http('realtime/getRealTimeData.html', 'deviceId=' + this.deviceId).subscribe(result => {
      let params = {
        programType: proType,
        deviceId: this.deviceId,
        version: result.data.version ? result.data.version : '',
        startDate: this.startTime_problem,
        endDate: this.endTime_problem,
        reason: operaParam.resultPhenStr,
        exceptionType: +this.proTypeParams.problemType + 1,
        repairedGuide: operaParam.repairGuideStr,
        isPush: this.isPush,
        coefficient: result.data.coef ? result.data.coef : ''
      }
      let reqdata = ''
      for (let keys in params) {
        reqdata = reqdata + keys + '=' + params[keys] + '&'
      }
      reqdata = reqdata.substring(0, reqdata.length - 1)
      this.jsonApiService.http('dataExceptionRecord/addDataException.html', reqdata).subscribe(result2 => {
        this.jsonApiService.message(result2.message)
        if (result2.success) {
          this.isDisable = false
          //					this.load();
        }
      })
    })
  }

  //提交到设备故障记录
  submitDevice() {
    if (!this.deviceId) {
      this.jsonApiService.message('先选择车辆...')
      return
    }
    if (!this.startTime_problem || !this.endTime_problem) {
      this.jsonApiService.message('问题起始时间不能为空...')
      return
    }
    let timeCheck = common.correctTimeParams(this.startTime_problem, this.endTime_problem, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let operaParam = this.getSelectedVAL()
    //		if(this.proTypeParams.problemType=='1'&&this.proTypeParams.problemClass=='1'){
    //			if(this.seneorPhenlist.length<1){
    //				this.jsonApiService.message('请确认添加传感器问题现象');
    //				return;
    //			}
    //		}
    if (this.proTypeParams.problemType == '1' && this.proTypeParams.problemClass == '1') {
      let sensor = $('#sensorPhenName').val()
      if (this.seneorPhenlist.length < 1 && !sensor && !this.proTypeParams.phenomenon) {
        this.jsonApiService.message('请确认添加传感器问题现象')
        return
      }
      if (sensor && this.proTypeParams.phenomenon) {
        let phen =
          this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name
        let phenResult = '传感器' + sensor + '-' + phen
        if (this.seneorPhenlist.length < 1) {
          operaParam.resultPhenStr = phenResult
        } else {
          let findIndex = operaParam.resultPhenStr.indexOf(phenResult)
          if (findIndex < 0) {
            operaParam.resultPhenStr = operaParam.resultPhenStr + ',' + phenResult
          }
        }
      }
    }
    if (!this.proTypeParams.problemType || !this.proTypeParams.problemClass) {
      this.jsonApiService.message('请选择问题分类')
      return
    }
    let proType = +this.proTypeParams.problemType + 1 + '0' + (+this.proTypeParams.problemClass + 1)
    if (operaParam.resultPhenStr == '') {
      this.jsonApiService.message('问题现象不能为空')
      return
    }

    let params = {
      programType: proType,
      deviceId: this.deviceId, //编号
      carNumber: this.carNumber || this.carNumberWeight.split(' ')[0], //车牌,地磅车牌，哪个有数据显示哪个
      faultTypeName: operaParam.problemClassStr, //故障类型
      faultTime: this.startTime_problem, //故障时间
      faultPhenomenon: operaParam.resultPhenStr, //故障现象:例  传感器1-平直
      isPush: this.isPush, //是否推送
      repairedGuide: operaParam.repairGuideStr, //维修指导
      repairedRecords: '', //维修记录
      repairedStatus: '', //维修状态(故障状态)
      repairedTime: '', //维修时间
      repairedUser: '', //维修人员
      remark: '', //备注
      repairedConclusion: '' //维修总结
    }

    let reqdata = ''
    for (let keys in params) {
      reqdata = reqdata + keys + '=' + params[keys] + '&'
    }
    reqdata = reqdata.substring(0, reqdata.length - 1)
    this.jsonApiService.http('deviceRepaired/validateRecord.html', 'deviceId=' + this.deviceId).subscribe(result => {
      if (result.valid) {
        this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
          this.jsonApiService.http('deviceRepaired/insertDeviceRepaired.html', reqdata).subscribe(result => {
            this.jsonApiService.message(result.message)
            if (result.success) {
              //							this.load();
            }
          })
        })
      } else {
        this.jsonApiService.http('deviceRepaired/insertDeviceRepaired.html', reqdata).subscribe(result => {
          this.jsonApiService.message(result.message)
          if (result.success) {
            //						this.load();
          }
        })
      }
    })
  }

  /**
   * 记录传感器损坏模块开关
   */
  sensorChannelChange() {
    this.sensorChannel = !this.sensorChannel
    if (this.sensorChannel) {
      this.sensorLoad()
    }
  }
  /**
   * 通道选择change事件,处理数据,记录选择通道
   */
  sensorChange(id, e) {
    if (e.target.checked) {
      this.sensorArr[id - 1].checked = true
    } else {
      this.sensorArr[id - 1].checked = false
    }
  }
  /*
   * 记录传感器提交
   */
  submitSensor() {
    if (!this.deviceId) {
      this.jsonApiService.message('请选择车辆')
      return
    }
    if (!this.startTime_sensor) {
      this.jsonApiService.message('请输入传感器损坏开始时间')
    }
    if (this.startTime_sensor && this.endTime_sensor) {
      let timeCheck = common.correctTimeParams(this.startTime_sensor, this.endTime_sensor, 0)
      if (!timeCheck.status) {
        this.jsonApiService.message(timeCheck.message)
        return
      }
    }

    let channels: any = []
    for (let item of this.sensorArr) {
      if (item.checked) {
        channels.push(item.id)
      }
    }
    if (!channels.length) {
      this.jsonApiService.message('请选择传感器通道')
      return
    }
    let reqdata = {
      carNumber: this.carNumber,
      deviceId: this.deviceId,
      startTime: this.startTime_sensor,
      endTime: this.endTime_sensor,
      channels: channels.join(',')
    }
    this.jsonApiService.http_obj('sensorMarkDamage/addSensorMarkDamage.html', reqdata).subscribe(result => {
      this.jsonApiService.message(result.message)
      if (result.success) {
        this.sensorLoad()
      }
    })
  }
  /**
   * 单个设备传感器损坏记录
   */
  sensorLoad() {
    if (!this.deviceId) {
      this.jsonApiService.message('请选择车辆')
      return
    }
    let data = {
      pageSize: 20,
      nowPage: 1,
      parameters: {
        deviceId: this.deviceId
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('sensorMarkDamage/sensorMarkDamageForPage.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.sensorTableData = data.exhibitDatas
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  /*
   * 传感器损坏记录删除
   */
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http_obj('sensorMarkDamage/deleteSensorMarkDamage.html', { id: row.id }).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.sensorLoad()
        }
      })
    })
  }
  /**
   * 设备电压信息开关,this.voltage为true显示,false隐藏
   */
  voltageChange() {
    var passageDataArouse = JSON.parse(JSON.stringify(this.passageData))
    if (this.voltage) {
      this.dealVoltageData()
    } else {
      for (var i = 0; i < passageDataArouse.length; i++) {
        if (passageDataArouse[i].name == '设备电压 (v)') {
          passageDataArouse.splice(i, 1)
          break
        }
      }
      for (var i = 0; i < passageDataArouse.length; i++) {
        if (passageDataArouse[i].name == '锂电池电压 (v)') {
          passageDataArouse.splice(i, 1)
          break
        }
      }
      for (var i = 0; i < passageDataArouse.length; i++) {
        if (passageDataArouse[i].name == '电池容量') {
          passageDataArouse.splice(i, 1)
          break
        }
      }
      this.passageData = JSON.parse(JSON.stringify(passageDataArouse))
    }

    this.echartOption.series = this.passageData
    this.myChart.setOption(this.echartOption, true)
  }
  /**
   * 电压采样半小时一个点,对电压数据值进行补点,处理成和历史数据X轴点数对应;
   * 补点原理:电压两点之前补前面一个点的值,电压最后一个点之后,补最后一个点值;
   */
  dealVoltageData() {
    this.voltageDataEchart = []
    var voltageForLiEchart = []
    var BatteryPerEchart = []
    var index = 0
    var volIndex = 0
    for (var i = 0; i < this.voltageData.length - 1; i++) {
      var temTime1 = common.mmsstoTimestamp(this.voltageData[i].uploadDate)
      var temTime2 = common.mmsstoTimestamp(this.voltageData[i + 1].uploadDate)
      for (var j = index; j < this.allData.length - 1; j++) {
        var temTime3 = common.mmsstoTimestamp(this.allData[j].uploadDate)
        var temTime4 = common.mmsstoTimestamp(this.allData[j + 1].uploadDate)
        index = j
        volIndex = i
        if (temTime3 >= temTime1 && temTime2 >= temTime3) {
          //两点之间补点
          this.voltageDataEchart.push(this.voltageData[i].voltage)
          //锂电池电压：voltageForLi
          //电池容量：batteryPer
          //电池容量（batteryPer）等于100时，显示充电中，其他显示数值（包括0）
          let voltageForLi = this.voltageData[i].voltageForLi == null ? '--' : this.voltageData[i].voltageForLi
          voltageForLiEchart.push(voltageForLi)
          if (this.voltageData[i].batteryPer == 100) {
            var batteryPer = '充电中'
            BatteryPerEchart.push(batteryPer)
          } else {
            BatteryPerEchart.push(this.voltageData[i].batteryPer)
          }
        } else if (temTime3 < temTime1 && !this.voltageData[i - 1]) {
          //电压第一个点在数据范围之内,该点之前补点,补空数据
          this.voltageDataEchart.push('--')
          voltageForLiEchart.push('--')
          BatteryPerEchart.push('--')
        } else if (temTime3 < temTime1 && this.voltageData[i - 1]) {
          //电压最后一点在数据范围之外后,该点之前补点,补上一个点
          this.voltageDataEchart.push(this.voltageData[i - 1].voltage)
          let voltageForLi = this.voltageData[i - 1].voltageForLi == null ? '--' : this.voltageData[i - 1].voltageForLi
          voltageForLiEchart.push(voltageForLi)
          if (this.voltageData[i - 1].batteryPer == 100) {
            var batteryPer = '充电中'
            BatteryPerEchart.push(batteryPer)
          } else {
            BatteryPerEchart.push(this.voltageData[i - 1].batteryPer)
          }
        } else if (temTime3 > temTime2 && i < this.voltageData.length - 2) {
          //最后一个点之前跳出循环
          if (temTime1 >= this.allData[0]) {
            if (temTime4 - temTime3 > temTime2 - temTime1) {
              //处理电压连续两点差值小于历史数据两点差值
              this.voltageDataEchart.push(this.voltageData[i].voltage)
              let voltageForLi = this.voltageData[i].voltageForLi == null ? '--' : this.voltageData[i].voltageForLi
              voltageForLiEchart.push(voltageForLi)
              if (this.voltageData[i].batteryPer == 100) {
                var batteryPer = '充电中'
                BatteryPerEchart.push(batteryPer)
              } else {
                BatteryPerEchart.push(this.voltageData[i].batteryPer)
              }
              break
            }
          } else {
            break
          }
        } else {
          this.voltageDataEchart.push(this.voltageData[i].voltage)
          let voltageForLi = this.voltageData[i].voltageForLi == null ? '--' : this.voltageData[i].voltageForLi
          voltageForLiEchart.push(voltageForLi)
          if (this.voltageData[i].batteryPer == 100) {
            var batteryPer = '充电中'
            BatteryPerEchart.push(batteryPer)
          } else {
            BatteryPerEchart.push(this.voltageData[i].batteryPer)
          }
        }
      }
    }
    if (this.allData.length - this.voltageDataEchart.length == 1) {
      //处理最一点的值
      this.voltageDataEchart.push(this.voltageData[volIndex].voltage)
      let voltageForLi =
        this.voltageData[volIndex].voltageForLi == null ? '--' : this.voltageData[volIndex].voltageForLi
      voltageForLiEchart.push(voltageForLi)
      if (this.voltageData[volIndex].batteryPer == 100) {
        var batteryPer = '充电中'
        BatteryPerEchart.push(batteryPer)
      } else {
        BatteryPerEchart.push(this.voltageData[volIndex].batteryPer)
      }
    }
    if (this.voltageData.length >= 1) {
      let obj = {
        name: '设备电压 (v)',
        type: 'line',
        yAxisIndex: 0,
        show: true,
        data: this.voltageDataEchart,
        itemStyle: {
          color: 'orange'
        }
      }
      this.passageData.push(obj)
      let voltageFoObj = {
        name: '锂电池电压 (v)',
        type: 'line',
        yAxisIndex: 0,
        show: false,
        data: voltageForLiEchart,
        lineStyle: {
          opacity: 0
        },
        itemStyle: {
          color: '#2fcdf1',
          opacity: 0
        }
      }
      this.passageData.push(voltageFoObj)
      let batteryPerObj = {
        name: '电池容量',
        type: 'line',
        yAxisIndex: 0,
        show: false,
        data: BatteryPerEchart,
        lineStyle: {
          opacity: 0
        },
        itemStyle: {
          color: '#4ff57a',
          opacity: 0
        }
      }
      this.passageData.push(batteryPerObj)
    }
  }

  /**
   * 设备详细    导航tab切换
   */
  tableDataTab1: any = []
  tableDataTab2: any = []
  tableDataTab2_1: any = []
  tableDataTab3: any = []
  tableDataTab4_1: any = []
  tableDataTab4_2: any = []
  tableDataTab5: any = []
  tableDataTab6: any = []
  tableDataTab7: any = [] //磅单数据
  totalCountTab: number = 0
  pageSizeTab: number = 10
  curPageTab: number = 1 //分页当前页
  activeTab: string = ''
  btnGroupActive: string = '5' //快捷时间按钮(默认三个月);
  btnGroupActiveText: string = '近三个月' //快捷时间按钮文字
  startDateBtn: string = ''
  endDateBtn: string = ''
  /**
   * 时间快捷选择方式:一周/半个月/一个月/两个月/三个月
   */
  selectTimeFast(val) {
    this.btnGroupActive = val
    let temDate = new Date()
    switch (val) {
      case '1':
        this.btnGroupActiveText = '近一周'
        temDate.setDate(temDate.getDate() - 7) //近一周
        this.startDateBtn = common.getTimeMmss(temDate)
        this.endDateBtn = common.getNowTime()
        break
      //			case '2':
      //				this.btnGroupActiveText = '近半个月';
      //				temDate.setDate(temDate.getDate() - 15);//近半个月
      //				this.startDateBtn = common.getTimeMmss(temDate);
      //				this.endDateBtn = common.getNowTime();
      //				break;
      case '3':
        this.btnGroupActiveText = '近一个月'
        temDate.setMonth(temDate.getMonth() - 1) //近一个月
        this.startDateBtn = common.getTimeMmss(temDate)
        this.endDateBtn = common.getNowTime()
        break
      //			case '4':
      //				this.btnGroupActiveText = '近两个月';
      //				temDate.setDate(temDate.getDate() - 60);//近两个月
      //				this.startDateBtn = common.getTimeMmss(temDate);
      //				this.endDateBtn = common.getNowTime();
      //				break;
      case '5':
        this.btnGroupActiveText = '近三个月'
        temDate.setMonth(temDate.getMonth() - 3) //近三个月
        this.startDateBtn = common.getTimeMmss(temDate)
        this.endDateBtn = common.getNowTime()
        break
      case '6':
        this.btnGroupActiveText = '近半年'
        temDate.setMonth(temDate.getMonth() - 6) //近半年
        this.startDateBtn = common.getTimeMmss(temDate)
        this.endDateBtn = common.getNowTime()
        break
      case '7':
        this.btnGroupActiveText = '全部'
        // temDate.setFullYear(temDate.getFullYear() - 1) //近一年
        this.startDateBtn = '2017-01-01 00:00:00'
        this.endDateBtn = common.getNowTime()
        break
      default: //默认近三个月
        this.btnGroupActive = '5'
        this.btnGroupActiveText = '近三个月'
        temDate.setDate(temDate.getDate() - 90)
        this.startDateBtn = common.getTimeMmss(temDate)
        this.endDateBtn = common.getNowTime()
        break
    }
    this.getDeviceInfoData()
    this.getTableDataTab(this.activeTab)
  }
  getTabData(type) {
    this.tableDataTab1 = []
    this.tableDataTab2 = []
    this.tableDataTab2_1 = []
    this.tableDataTab3 = []
    this.tableDataTab3 = []
    this.tableDataTab4_1 = []
    this.tableDataTab4_2 = []
    this.tableDataTab5 = []
    this.tableDataTab6 = []
    this.tableDataTab7.length = 0
    this.totalCountTab = 0
    this.pageSizeTab = 10
    this.curPageTab = 1
    this.activeTab = type
    this.getTableDataTab(type)
  }
  //获取数据:故障信息/维修信息/警报信息/数据修复/固件升级/系数设置
  versionUpdataCount: number
  coefUpdataCount: number
  fix: any = {
    totalCount: 0,
    mainCount: 0,
    sensorCount: 0,
    lineCount: 0,
    gpsCount: 0,
    mainQuestion: 0,
    sensorQuestion: 0,
    lineQuestion: 0,
    gpsQuestion: 0,
    firstFixQuestion: '',
    firstFixQuestionTime: '',
    firstSensorQuestion: '',
    firstSensorQuestionTime: '',
    lastSensorQuestion: '',
    lastSensorQuestionTime: '',
    lastGPSQuestion: '',
    lastGPSQuestionTime: ''
  }
  timelineDate: any = []
  getTableDataTab(type) {
    let reqData: any, param: any
    switch (type) {
      case '':
        this.getDeviceInfoData()
        break
      case '1':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            deviceId: this.deviceId,
            carNumber: this.selectRowData.carNumber,
            startDate: this.startDateBtn,
            endDate: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('dataExceptionRecord/dataRecordPage.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          for (let item of result.exhibitDatas) {
            item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1)
            item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2)
            item.exceptionType = this.getExceptionTypeName(item.exceptionType)
            item.programType = this.getProgramTypeName(item.programType)
            if (item.coefficient) {
              let coefArr = []
              for (let i = 0; i < item.coefficient.length; i++) {
                let _item = item.coefficient[i]
                if (_item && _item != '0') {
                  var obj = {
                    value: item.coefficient[i],
                    index: i + 1
                  }
                  coefArr.push(obj)
                }
              }
              item.coef = coefArr
            } else {
              item.coef = []
            }
          }
          this.tableDataTab1 = result.exhibitDatas
          this.totalCountTab = result.recordCount
        })
        break
      case '2':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            searchKey: this.deviceId,
            startTime: this.startDateBtn,
            endTime: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('fixdatalog/logforpage.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          this.tableDataTab2 = result.exhibitDatas
          this.totalCountTab = result.recordCount
        })
        break
      case '2_1':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            searchKey: this.deviceId,
            startDate: this.startDateBtn,
            endDate: this.endDateBtn,
            status: '0'
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('exceptionOrderForHaiLuo/findExceptionOrderList.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          this.tableDataTab2_1 = result.exhibitDatas
          this.totalCountTab = result.recordCount
        })
        break
      case '3':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            deviceId: this.deviceId,
            startTime: this.startDateBtn,
            endTime: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('alertlog/deviceShutDownAlarm.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          if (type == '3') {
            for (let item of result.exhibitDatas) {
              item.totalSecond = common.secondToDate(item.totalSecond)
            }
          }
          this.tableDataTab3 = result.exhibitDatas
          this.totalCountTab = result.recordCount
        })
        break
      case '4_1':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            deviceId: this.deviceId,
            repairedStatus: '0',
            dateType: '1',
            startDate: this.startDateBtn,
            endDate: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('deviceRepaired/findDeviceRepairedList.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          if (result.exhibitDatas.length > 0) {
            for (var i = 0; i < result.exhibitDatas.length; i++) {
              result.exhibitDatas[i].restrictTimeFlag = false
              if (result.exhibitDatas[i].restrictTime) {
                if (
                  common.mmsstoTimestamp(common.getNowTime()) -
                  common.mmsstoTimestamp(result.exhibitDatas[i].restrictTime) <
                  0
                ) {
                  result.exhibitDatas[i].restrictTimeFlag = true
                }
              }
            }
          }
          this.tableDataTab4_1 = result.exhibitDatas || []
          this.tableDataTab4_1.map(item => (item.callDuration = common.secondToDate(item.callDuration)))
          this.totalCountTab = result.recordCount
        })
        break
      case '4_2':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            deviceId: this.deviceId,
            sortType: '2',
            startDate: this.startDateBtn,
            endDate: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('deviceRepairedV2/findDeviceRepairedV2List.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          this.tableDataTab4_2 = result.exhibitDatas || []
          for (let item of this.tableDataTab4_2) {
            var faultPhenomenonList = item.faultPhenomenonList && Array.from(new Set(item.faultPhenomenonList))
            item.faultPhenomenonList = faultPhenomenonList.length > 0 ? faultPhenomenonList.join(',') : ''

            var repairContentList = item.repairContentList && Array.from(new Set(item.repairContentList))
            item.repairContentList = repairContentList.length > 0 ? repairContentList.join(',') : ''

            var repairSubdivideList = item.repairSubdivideList && Array.from(new Set(item.repairSubdivideList))
            item.repairSubdivideList = repairSubdivideList.length > 0 ? repairSubdivideList.join(',') : ''

            item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2)
          }
          this.totalCountTab = result.recordCount
          this.repairedDeviceInfo.fixedCount = result.recordCount
        })
        break
      case '5':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            deviceId: this.deviceId,
            startTime: this.startDateBtn,
            endTime: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('log/upgrade.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          this.tableDataTab5 = result.exhibitDatas || []
          this.totalCountTab = result.recordCount
        })
        break
      case '6':
        reqData = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            deviceId: this.deviceId,
            startTime: this.startDateBtn,
            endTime: this.endDateBtn
          }
        }
        param = 'gridPager=' + JSON.stringify(reqData)
        this.jsonApiService.http('deviceCoefLog/deviceCoefLogforpage.html', param).subscribe(result => {
          if (!result.isSuccess) {
            this.jsonApiService.message(result.message)
            return
          }
          for (let item of result.exhibitDatas) {
            if (item.newCoef) {
              let newCoef = []
              for (let i = 0; i < item.newCoef.length; i++) {
                let _item = item.newCoef[i]
                if (_item) {
                  let obj: any = {
                    value: item.newCoef[i],
                    index: i + 1
                  }
                  newCoef.push(obj)
                }
              }
              item.newCoef = newCoef
            } else {
              item.newCoef = []
            }

            if (item.oldCoef) {
              let oldCoef = []
              for (let i = 0; i < item.oldCoef.length; i++) {
                let _item = item.oldCoef[i]
                if (_item) {
                  let obj: any = {
                    value: item.oldCoef[i],
                    index: i + 1
                  }
                  oldCoef.push(obj)
                }
              }
              item.oldCoef = oldCoef
            } else {
              item.oldCoef = []
            }
          }
          this.tableDataTab6 = result.exhibitDatas || []
          this.totalCountTab = result.recordCount
        })
        break
      case '7':
        let reqdata: any = {
          pageSize: this.pageSizeTab,
          nowPage: this.curPageTab,
          parameters: {
            companyId: this.selectedCompanyId,
            carNumber: this.carNumber || this.carNumberWeight.split(' ')[0],
            startTime: this.startDateBtn,
            endTime: this.endDateBtn,
            deviceId: this.deviceId
          }
        }
        reqdata = 'gridPager=' + JSON.stringify(reqdata)
        this.jsonApiService.http('weighbridge/list.html', reqdata).subscribe(data => {
          this.tableDataTab7 = data.exhibitDatas
          this.totalCount = data.recordCount
        })
        break
      case '8':
        this.addHostAndSensor() //主机和传感器
        // reqData = 'deviceId=' + this.deviceId
        // this.jsonApiService.http('eventMonitor/eventDataList.html', reqData).subscribe(data => {
        //   if (data.success && data.data) {
        //     this.coefUpdataCount = 0
        //     this.versionUpdataCount = 0
        //     this.fix = {
        //       totalCount: 0,
        //       mainCount: 0,
        //       sensorCount: 0,
        //       lineCount: 0,
        //       gpsCount: 0,
        //       mainQuestion: 0,
        //       sensorQuestion: 0,
        //       lineQuestion: 0,
        //       gpsQuestion: 0,
        //       firstFixQuestion: '',
        //       firstFixQuestionTime: '',
        //       firstSensorQuestion: '',
        //       firstSensorQuestionTime: '',
        //       lastSensorQuestion: '',
        //       lastSensorQuestionTime: '',
        //       lastGPSQuestion: '',
        //       lastGPSQuestionTime: ''
        //     }
        //     let result = data.data
        //     let sensorObj = {}
        //     for (let item of result) {
        //       item.eventType1 == 4 ? (this.coefUpdataCount += 1) : (this.coefUpdataCount = this.coefUpdataCount)
        //       item.eventType1 == 3
        //         ? (this.versionUpdataCount += 1)
        //         : (this.versionUpdataCount = this.versionUpdataCount)
        //       item.eventType2 != 0 ? (this.fix.totalCount += 1) : (this.fix.totalCount = this.fix.totalCount)
        //       item.eventType2Name == '更换主机' ? (this.fix.mainCount += 1) : (this.fix.mainCount = this.fix.mainCount)
        //       item.eventType2Name == '更换传感器'
        //         ? (this.fix.sensorCount += 1)
        //         : (this.fix.sensorCount = this.fix.sensorCount)
        //       item.eventType2Name == '更换线材' ? (this.fix.lineCount += 1) : (this.fix.lineCount = this.fix.lineCount)
        //       item.eventType2Name == '更换GPS' ? (this.fix.gpsCount += 1) : (this.fix.gpsCount = this.fix.gpsCount)
        //       if (item.eventType2 != 0) {
        //         item.eventType2 == 202
        //           ? (this.fix.firstFixQuestion = null)
        //           : (this.fix.firstFixQuestion = item.eventContent)
        //         this.fix.firstFixQuestionTime = item.eventTime
        //       }
        //       if (item.eventType2 == 202) {
        //         this.fix.firstSensorQuestion = item.eventContent
        //         this.fix.firstSensorQuestionTime = item.eventTime
        //         // 增加传感器问题列表
        //         let arr = item.eventContent.split('-')
        //         if (arr.length > 1) {
        //           // 切分出管道号
        //           let channel = arr[arr.length - 1]
        //           item.text1 = '第一次维修CH' + channel
        //           item.text2 = '第一次维修CH' + channel + '时间'
        //           if (sensorObj[channel]) {
        //             // 同一管道只保留最新的数据
        //             let oldTime = sensorObj[channel].eventTime.replace(/-/g, '/')
        //             let newTime = item.eventTime.replace(/-/g, '/')
        //             if (new Date(oldTime).valueOf() > new Date(newTime).valueOf()) {
        //               sensorObj[channel] = item
        //             }
        //           } else {
        //             sensorObj[channel] = item
        //           }
        //         }
        //       }
        //       if (item.eventType2 == 202 && !this.fix.lastSensorQuestion) {
        //         this.fix.lastSensorQuestion = item.eventContent
        //         this.fix.lastSensorQuestionTime = item.eventTime
        //       }
        //       if (item.eventType2 == 204 && !this.fix.lastGPSQuestion) {
        //         this.fix.lastGPSQuestion = item.eventContent
        //         this.fix.lastGPSQuestionTime = item.eventTime
        //       }
        //     }
        //     // 传感器对象进行排序并变成数组的格式
        //     let sensorArr = Object.keys(sensorObj).reduce(function (arr: any, k) {
        //       arr.push(sensorObj[k])
        //       return arr
        //     }, [])
        //     // 给页面的变量赋值
        //     this.sensorList = sensorArr.sort(function (a, b) {
        //       let oldTime = a.eventTime.replace(/-/g, '/')
        //       let newTime = b.eventTime.replace(/-/g, '/')
        //       if (new Date(oldTime).valueOf() < new Date(newTime).valueOf()) {
        //         return -1
        //       }
        //     })

        //     var year = new Date().getFullYear()
        //     let obj: any
        //     this.timelineDate = []
        //     for (let i = 2015; i < year + 1; i++) {
        //       let chrildArr: any = []
        //       obj = null
        //       for (let item of result) {
        //         if (item.eventYear == i) {
        //           chrildArr.push(item)
        //           obj = {
        //             date: item.eventYear + '',
        //             chrild: chrildArr,
        //             isShow: true
        //           }
        //         }
        //       }
        //       if (obj) {
        //         this.timelineDate.push(obj)
        //       }
        //     }
        //     this.timelineDate = this.timelineDate.reverse()
        if (this.deviceBaseInfo.inputDate) {
          this.deviceBaseInfo.installTime = common.secondToDate(
            (common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceBaseInfo.inputDate)) /
            1000
          )
        }
        // 获取其他的数据接口
        this.jsonApiService.http_obj('system/getRealTimeData.html', { deviceId: this.deviceId }).subscribe(data => {
          this.otherData = data.data
        })
        //   }
        // })
        break
      default:
        this.getDeviceInfoData()
        break
    }
  }
  /**
   * 设备事件 新增主机生命周期和传感器生命周期
   */
  hostTableData: any = [] //主机table列表
  sensorListData: any = [] //传感器table列表
  sensorCount: string = '' //传感器数量
  addHostAndSensor() {
    this.jsonApiService.http_get('matterReplaceInfo/queryMatterReplaceInfoListByDeviceId.html?deviceId=' + this.deviceId).subscribe(data => {
      if (data.success && data.data) {
        let result = data.data
        this.hostTableData = result.hostList || []
        this.sensorListData = result.sensorList ? this.mergeData(result.sensorList, "materielNumber") : []
        this.sensorCount = result.sensorCount
      }
    })
  }
  mergeData(data, indexName) {
    if (data == undefined || data.length == 0 || data == null) {
      return;
    }
    let res = [] //结果数组
    let rowSpan = 1
    for (let i = 0; i < data.length; i++) {
      for (let j = i + 1; j < data.length; j++) {
        if (data[i][indexName] == data[j][indexName]) {
          rowSpan++;
        } else {
          break;
        }
      }
      //开始复制某组相同的数据
      if (rowSpan > 1) {
        for (let k = 0; k < rowSpan; k++) {
          data[k + i].secondIndex = k;
          data[k + i].rowSpan = rowSpan;
          res.push(data[k + i])
        }
        i += (rowSpan - 1) //跳过相同的数据
        rowSpan = 1;
      } else {
        //复制单独的数据
        data[i].secondIndex = 0;
        data[i].rowSpan = rowSpan;
        res.push(data[i])
      }
    }
    return res
  }
  refreshTab() {
    this.getTabData(this.activeTab)
  }
  //分页回调
  paginateTab(e) {
    this.curPageTab = e.page + 1
    this.pageSizeTab = e.rows
    this.getTableDataTab(this.activeTab)
  }
  //根据编码映射对应车辆类型名称
  getUseTypeNameL1(key) {
    if (key) {
      return this.TcarUseList[key]
    } else {
      return ''
    }
  }
  //根据编码映射对应车辆类型名称
  getUseTypeNameL2(key) {
    if (key) {
      return this.TcarDeatailUseList[key]
    } else {
      return ''
    }
  }
  //问题分类
  getExceptionTypeName(key) {
    if (key) {
      return this.questionNameList[key]
    } else {
      return ''
    }
  }
  //现象分类
  getProgramTypeName(key) {
    if (key) {
      return this.questionDeatailNameList[key]
    } else {
      return ''
    }
  }
  questionNameList: any = {
    '1': '算法问题',
    '2': '硬件问题',
    '3': '司机问题',
    '4': '对接问题',
    '5': '运维问题',
    '6': '安装问题'
  }
  questionDeatailNameList: any = {
    '100': '其他',
    '101': '上货问题',
    '102': '卸货问题',
    '103': '在途问题',
    '104': '多次上货',
    '105': '多次卸货',
    '200': '其他',
    '201': '主机问题',
    '202': '传感器问题',
    '203': 'GPS问题',
    '204': '线材问题',
    '300': '其他',
    '301': '司机问题',
    '400': '其他',
    '401': '对接问题',
    '500': '其他',
    '501': '运维问题',
    '601': '安装问题',
    '600': '其他'
  }
  TcarUseList = carTypeListObj.carUseList
  TcarDeatailUseList = carTypeListObj.carDeatailUseList
  algorithmQuestionList: any = [
    {
      exceptionType: '1',
      programType: '101',
      faultTypeName: '算法问题',
      text: '上货问题',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '104',
      faultTypeName: '算法问题',
      text: '多次上货',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '102',
      faultTypeName: '算法问题',
      text: '卸货问题',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '105',
      faultTypeName: '算法问题',
      text: '多次卸货',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '103',
      faultTypeName: '算法问题',
      text: '在途问题',
      selected: false
    }
  ]
  /**
   * 设备详细(设备基本信息/故障信息/维修信息/警报信息/数据修复)
   */
  selectRowData: any = {
    companyName: '',
    companyId: '',
    deviceId: '',
    carNumber: ''
  } //选中数据查看的数据row
  deviceDetail() {
    if (!this.deviceId) {
      this.jsonApiService.message('请选择要查看的车辆')
      return
    }
    $('#deviceDetailModal').show()
    $('.s-lis').removeClass('active')
    $('.tab-pane').removeClass('active')
    $('.s-lis').eq(0).addClass('active')
    $('.s-lis').eq(0).find('a').attr('aria-expanded', 'true')
    $('#all').eq(0).addClass('active')
    this.btnGroupActive = '5'
    let temDate = new Date()
    temDate.setDate(temDate.getDate() - 90) //默认近三个月
    this.startDateBtn = common.getTimeMmss(temDate)
    this.endDateBtn = common.getNowTime()
    this.getDeviceInfoData()
    this.getTableDataTab('7') //渲染磅单表格
  }
  /**
   * 关闭设备详情弹窗
   */
  cancelDeviceDetail() {
    $('#deviceDetailModal').hide()
  }
  tableMove() {
    $('body').delegate('#headDrag', 'mousedown', function (e) {
      $(this).css('cursor', 'move')
      var offset = $('#deviceDetailModal').position()
      var x = e.pageX - offset.left
      var y = e.pageY - offset.top
      $(document).bind('mousemove', function (ev) {
        $('#deviceDetailModal').stop()
        var _x = ev.pageX - x
        var _y = ev.pageY - y
        $('#deviceDetailModal').animate({ left: _x + 'px', top: _y + 'px' }, 2)
      })
    })
    $(document).mouseup(function () {
      //	        $(".hold-all").css("cursor","default");
      $('#deviceDetailModal').css('cursor', 'default')
      $(this).unbind('mousemove')
    })
    //      $('body').delegate('.hold-title','mousedown',function(e){
    //          $(this).css("cursor","move");
    //          var offset = $('.hold-all').position();
    //          var x = e.pageX - offset.left;
    //          var y = e.pageY - offset.top;
    //          $(document).bind("mousemove",function(ev){
    //              $(".hold-all").stop();
    //              var _x = ev.pageX - x;
    //              var _y = ev.pageY - y;
    //              $(".hold-all").animate({left:_x+"px",top:_y+"px"},2);
    //          });
    //      });
  }
  /**
   * 获取设备信息 (设备基本信息/故障信息/维修信息/警报信息/数据修复)
   */
  deviceBaseInfo: any = {
    companyName: '',
    carNumber: '',
    deviceId: '',
    hwVersion: '',
    useTypeL1: '',
    useTypeL2: '',
    userTypeName: '',
    sensorType: '',
    productNo: '',
    iccid: '',
    driverName: '',
    phone: '',
    inputDate: '',
    userNameForCreate: '',
    sensorChannel: [],
    coef: [],
    coefT: [],
    version: ''
  }
  questionRecordInfo: any = [] //问题记录
  questionRecordTotal: number = 0 //问题记录总和
  dataFixInfo: any = {} //数据修复
  alertDataInfo: any = {} //警报数据
  repairedDeviceInfo: any = {} //维修记录
  deviceRealTimeDataInfo: any = {} //设备实时数据
  isShowGPSAlert: boolean = false //是否显示GPS数据更新异常警报提示
  isShowOfflineAlert: boolean = false //是否显示离线警报提示
  offlineDiffTime: string = '' //离线时长
  weightCount: number = 0 //过磅次数

  weightData: any = {
    //总磅单数
    WeightBridgeCount: '',
    weight: '',
    lastDate: ''
  }

  initDeviceBasicInfo() {
    this.deviceBaseInfo = {
      companyName: '',
      carNumber: '',
      deviceId: '',
      hwVersion: '',
      useTypeL1: '',
      useTypeL2: '',
      userTypeName: '',
      sensorType: '',
      productNo: '',
      iccid: '',
      driverName: '',
      phone: '',
      inputDate: '',
      userNameForCreate: '',
      sensorChannel: [],
      coef: [],
      coefT: [],
      version: ''
    }
    this.renewalInfo = {}
  }
  expireTime = '' //过期天数
  //设备基本信息
  getDeviceBasicInfo(isModal = false) {
    // 初始化数据
    this.initDeviceBasicInfo()
    this.jsonApiService
      .http_obj('system/getDeviceBaseInfoByDeviceId.html', {
        deviceId: this.deviceId,
        factoryId: this.selectedCompanyId
      })
      .subscribe(data => {
        if (data.success && data.data) {
          if (data.data.projectCarInfo) {
            this.renewalInfo = JSON.parse(JSON.stringify(data.data.projectCarInfo))
            // 过期判断
            $('#overdueModal').hide()
            if (this.renewalInfo.renewalDueTime) {
              let date = new Date()
              let now = date.getTime()
              let overlineDate = new Date(this.renewalInfo.renewalDueTime).getTime()
              if (overlineDate > now) {
                this.renewalInfo.isOverDate = '未到期'
              } else {
                this.renewalInfo.isOverDate = '已到期'
                this.expireTime = '过期' + this.renewalInfo.remainingDay.slice(1, this.renewalInfo.remainingDay.length)
                // if (isModal) $('#overdueModal').show()
              }
            }
          }
          for (let item in this.deviceBaseInfo) {
            if (item === 'coef' || item === 'coefT' || item === 'sensorChannel') {
              this.deviceBaseInfo[item] = data.data[item] || []
            } else {
              this.deviceBaseInfo[item] = data.data[item] || ''
            }
          }
          this.deviceBaseInfo.userTypeName = this.getUseTypeNameL2(this.deviceBaseInfo.useTypeL2)
          if (this.deviceBaseInfo.coef) {
            let coefArr = []
            for (let i = 0; i < this.deviceBaseInfo.coef.length; i++) {
              let _item = this.deviceBaseInfo.coef[i]
              if (_item) {
                let obj: any = {
                  value: _item,
                  index: i + 1
                }
                coefArr.push(obj)
              }
            }
            this.deviceBaseInfo.coefT = coefArr
          } else {
            this.deviceBaseInfo.coefT = []
          }
        }
      })
  }
  closeOverdueModal() {
    $('#overdueModal').hide()
  }
  initDeviceBaseInfo() {
    this.isShowGPSAlert = false
    this.isShowOfflineAlert = false
    this.questionRecordInfo = []
    this.questionRecordTotal = 0
    this.dataFixInfo = {}
    this.alertDataInfo = {}
    this.repairedDeviceInfo = {}
    this.deviceRealTimeDataInfo = {}
    this.offlineDiffTime = ''
    this.weightCount = 0
  }
  getDeviceInfoData() {
    this.initDeviceBaseInfo()
    //设备基本信息
    this.getDeviceBasicInfo()
    //问题统计(近三个月)
    this.jsonApiService
      .http_obj('system/countDeviceDataRecordByDeviceId.html', {
        deviceId: this.deviceId,
        startDate: this.startDateBtn,
        endDate: this.endDateBtn
      })
      .subscribe(data => {
        if (data.success && data.data) {
          this.questionRecordTotal = 0
          this.questionRecordInfo = data.data
          for (let item of this.questionRecordInfo) {
            this.questionRecordTotal += +item.reasonCount
          }
        }
      })
    //数据修复统计(近三个月)
    this.jsonApiService
      .http_obj('system/queryDataFixCountByDeviceId.html', {
        deviceId: this.deviceId,
        startDate: this.startDateBtn,
        endDate: this.endDateBtn
      })
      .subscribe(data => {
        if (data.success && data.data) {
          this.dataFixInfo = data.data
        }
      })
    //警报统计(近三个月)
    this.jsonApiService
      .http_obj('system/queryAlarmCountByDeviceId.html', {
        deviceId: this.deviceId,
        startDate: this.startDateBtn,
        endDate: this.endDateBtn
      })
      .subscribe(data => {
        if (data.success && data.data) {
          this.alertDataInfo = data.data
        }
      })
    //维修记录统计(近三个月)
    this.jsonApiService
      .http_obj('system/queryDeviceRepairedByDeviceId.html', {
        deviceId: this.deviceId,
        startDate: this.startDateBtn,
        endDate: this.endDateBtn
      })
      .subscribe(data => {
        if (data.success && data.data) {
          this.repairedDeviceInfo = data.data
        }
      })
    //设备状态(实时数据)
    let deviceId = this.deviceId
    this.jsonApiService.http_obj('system/getRealTimeData.html', { deviceId: this.deviceId }).subscribe(data => {
      if (data.success && data.data) {
        this.deviceRealTimeDataInfo = data.data
        let carUploadDate, gpsUploadDate
        if (this.deviceRealTimeDataInfo.carUploadDate) {
          carUploadDate = this.deviceRealTimeDataInfo.carUploadDate
        }
        if (this.deviceRealTimeDataInfo.gpsUploadDate) {
          gpsUploadDate = this.deviceRealTimeDataInfo.gpsUploadDate
        }
        if (gpsUploadDate && carUploadDate) {
          let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate))
          abs >= 30 * 60 * 1000 ? (this.isShowGPSAlert = true) : (this.isShowGPSAlert = false) //计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
          this.getWeighbridge(deviceId)
        }
      }
    })
    // 总磅单数（近三个月）
    const reqDate = {
      deviceId: this.deviceId,
      startDate: this.startDateBtn,
      endDate: this.endDateBtn
    }
    this.jsonApiService.http_obj('system/queryWeightBridgeByDeviceId.html', reqDate).subscribe(result => {
      if (result.success) {
        this.weightData = result.data
      }
    })
  }
  //获取磅单数据:用于判断离线异常
  getWeighbridge(deviceId) {
    this.jsonApiService
      .http_obj('weighbridge/weightforreal.html', {
        deviceId: deviceId,
        startTime: this.deviceRealTimeDataInfo.updateTime,
        endTime: common.getNowTime()
      })
      .subscribe(data => {
        if (data.success && data.data) {
          this.weightCount = 0
          if (this.deviceRealTimeDataInfo.updateTime) {
            let diffTiem =
              common.mmsstoTimestamp(common.getNowTime()) -
              common.mmsstoTimestamp(this.deviceRealTimeDataInfo.updateTime)
            this.offlineDiffTime = common.secondToDate(diffTiem / 1000) //计算离线时长:当前时间 - 最后更新时间
            let weightData = data.data
            for (let item of weightData) {
              if (+item.weight > 0) {
                this.isShowOfflineAlert = true
                this.weightCount += 1 //计算榜单数
              }
            }
          }
        }
      })
  }
  /**
   * 问题记录跳转
   */
  jumpQuestionByHand(type1, type2, value) {
    if (value == 'total') {
      $('#myTab').find('li.s-lis').removeClass('active').find('.reqRecord').parent('li.s-lis').addClass('active')
      $('#all').removeClass('active')
      $('#question').addClass('active')
      this.getTabData('1')
      return false
    }

    if (value == 0) {
      this.jsonApiService.message('无记录!')
      return
    }
    $('#deviceDetailModal').hide()
    let queryParams = {
      companyName: this.selectRowData.companyName,
      companyId: this.selectRowData.companyId,
      deviceId: this.selectRowData.deviceId,
      carNumber: this.selectRowData.carNumber,
      startTime: this.startDateBtn,
      endTime: this.endDateBtn,
      exceptionType: type1,
      programType: type2
    }
    this.router.navigate(['/abnormal-alert/artificialMonitor'])
    common.setCookie('jumpQuestionByHandList', JSON.stringify(queryParams))
    setTimeout(function () {
      $('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none')
      $('#left-panel').find('.top-menu-invisible.open').removeClass('open')
      $('#left-panel').find('.top-menu-invisible.active').addClass('open')
      $('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block')
    }, 350)
  }
  /**
   * 设备警报跳转
   */
  jumpAlertDataList(type, value) {
    if (value == 'total') {
      this.getTabData('3')
      $('#myTab').find('li.s-lis').removeClass('active').find('.alertRecord').parent('li.s-lis').addClass('active')
      $('#all').removeClass('active')
      $('#alert').addClass('active')
      return false
    }

    if (!value) {
      this.jsonApiService.message('无记录!')
      return
    }
    $('#deviceDetailModal').hide()
    let queryParams = {
      companyName: this.selectRowData.companyName,
      companyId: this.selectRowData.companyId,
      deviceId: this.selectRowData.deviceId,
      carNumber: this.selectRowData.carNumber,
      startTime: this.startDateBtn,
      endTime: this.endDateBtn,
      type: type
    }
    this.router.navigate(['/abnormal-alert/device-off'])
    common.setCookie('jumpAlertDataList', JSON.stringify(queryParams))
    setTimeout(function () {
      $('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none')
      $('#left-panel').find('.top-menu-invisible.open').removeClass('open')
      $('#left-panel').find('.top-menu-invisible.active').addClass('open')
      $('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block')
    }, 350)
  }
  /**
   * 设备维修跳转
   */
  jumpRepairedDeviceList(type, dateType, value) {
    if (!value) {
      this.jsonApiService.message('无记录!')
      return
    }
    $('#deviceDetailModal').hide()
    let queryParams = {
      companyName: this.selectRowData.companyName,
      companyId: this.selectRowData.companyId,
      deviceId: this.selectRowData.deviceId,
      carNumber: this.selectRowData.carNumber,
      startTime: this.startDateBtn,
      endTime: this.endDateBtn,
      repairedStatus: type,
      dateType: dateType
    }
    if (type == '0') {
      this.router.navigate(['/device-management/fault'])
    } else if (type == '1') {
      this.router.navigate(['/device-management/faultV2'])
    }
    common.setCookie('jumpRepairedDeviceList', JSON.stringify(queryParams))
    setTimeout(function () {
      $('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none')
      $('#left-panel').find('.top-menu-invisible.open').removeClass('open')
      $('#left-panel').find('.top-menu-invisible.active').addClass('open')
      $('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block')
    }, 350)
  }
  jumpDataFixList(type, value) {
    if (!value) {
      this.jsonApiService.message('无记录!')
      return
    }
    $('#deviceDetailModal').hide()
    let queryParams = {
      companyName: this.selectRowData.companyName,
      companyId: this.selectRowData.companyId,
      deviceId: this.selectRowData.deviceId,
      carNumber: this.selectRowData.carNumber,
      startTime: this.startDateBtn,
      endTime: this.endDateBtn,
      type: null
    }
    switch (type) {
      case '1':
        queryParams.type = '1'
        this.router.navigate(['/log-info/repairRecord'])
        common.setCookie('jumpDataFixList', JSON.stringify(queryParams))
        break
      case '2':
        queryParams.type = '2'
        this.router.navigate(['/log-info/repairRecord'])
        common.setCookie('jumpDataFixList', JSON.stringify(queryParams))
        break
      case '3':
        queryParams.type = '0'
        this.router.navigate(['/abnormal-alert/order'])
        common.setCookie('jumpExceptionOrderList', JSON.stringify(queryParams))
        break
      default:
        break
    }
    setTimeout(function () {
      $('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none')
      $('#left-panel').find('.top-menu-invisible.open').removeClass('open')
      $('#left-panel').find('.top-menu-invisible.active').addClass('open')
      $('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block')
    }, 350)
  }

  /**
   *  有磅单车辆查询模块
   */
  deleteCarFlag: any = '' //删除标识
  carWeightList: any = [] //地磅数据车辆
  carNumberWeight: string = '' //地磅数据车辆车牌
  clearEventFlag: boolean = false //清除子组件上下键盘事件
  // 榜单select2
  //拉取车辆数据
  selectLoadometer() {
    var that = this
    $('#loadometerSelect')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        templateResult: this.formatRepo
      })
      .on('select2:select', function (e) {
        that.clearEventFlag = true
        that.keyCodeEvent()
        if (that.carNumber) {
          that.deleteCarFlag = new Date().getTime()
        }
        var data = e.params.data
        setTimeout(() => {
          that.deviceId = data.id
        }, 100)

        that.carNumberWeight = data.text
        let len = that.carList.length
        if (len > 1) {
          for (let x = 0; x < len; x++) {
            if (that.carNumberWeight == that.carList[x].text) {
              that.carIndexMsg = {
                allNums: len,
                index: x + 1,
                status: true
              }
              break
            }
          }
        } else {
          that.carIndexMsg.status = false
        }
      })
  }
  //公司id拉取车辆
  queryCarListByCompanyId() {
    // this.deviceId = '';
    // this.carNumber = '';
    // this.isAllowNext = false;
    // this.isAllowPre = false;
    this.carIndexMsg.status = false
    let reqdata = {
      companyId: this.selectedCompanyId,
      startTime: this.startTime,
      endTime: this.endTime
    }
    this.jsonApiService.http_obj('weighbridge/queryCarNumberWeightBridgeDownList.html', reqdata).subscribe(data => {
      var carlist = data.data
      var selectdata = []
      for (var i = 0; i < carlist.length; i++) {
        var obj = {
          id: carlist[i].deviceId,
          text: carlist[i].carNumber + ' [' + carlist[i].count + ']'
        }
        selectdata[i] = obj
      }
      this.carList = selectdata
      var selectObj = $('#loadometerSelect')
      this.clearSelect2(selectObj) //清除Select中的数据
      selectObj.select2({
        language: 'zh-CN',
        data: selectdata, //为Select添加数据
        templateResult: this.formatRepo
      })
    })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  clearSelect2(obj) {
    obj.empty()
    obj.prepend("<option value=''>请选择</option>")
  }
  //擦除车牌号码所选值
  del_loadometer() {
    this.deviceId = ''
    this.carNumberWeight = ''
    this.carIndexMsg.status = false
    if (this.companyId) {
      this.queryCarListByCompanyId()
    } else {
      //采用简单粗暴的方法清除;官方推荐的方法失效
      var str = $("<span class='select2-selection__placeholder'>请选择</span>")
      $('#loadometerSelect').val('')
      $('#select2-loadometerSelect-container').empty()
      $('#select2-loadometerSelect-container').attr('title', '')
      $('#select2-loadometerSelect-container').prepend(str)
    }
  }
  //selcet2  车辆
  nextCarLoad(type) {
    this.isAllowNext = false
    this.isAllowPre = false
    //		this.isDisable = true;
    if (this.carList.length > 1 && this.deviceId) {
      let len = this.carList.length
      for (let i = 0; i < len; i++) {
        if (this.carList[i].text === this.carNumberWeight && this.carList[i].id === this.deviceId) {
          if (type === 'pre') {
            if (i > 0) {
              this.carNumberWeight = this.carList[i - 1].text
              this.deviceId = this.carList[i - 1].id
              $('#loadometerSelect').val(this.deviceId).trigger('change')
              break
            } else {
              this.isAllowPre = true
              break
            }
          } else if (type === 'next') {
            if (i < len - 1) {
              this.carNumberWeight = this.carList[i + 1].text
              this.deviceId = this.carList[i + 1].id
              $('#loadometerSelect').val(this.deviceId).trigger('change')
              break
            } else {
              this.isAllowNext = true
              break
            }
          }
        }
      }
      for (let x = 0; x < len; x++) {
        if (this.carNumberWeight == this.carList[x].text) {
          this.carIndexMsg = {
            allNums: len,
            index: x + 1,
            status: true
          }
          break
        }
      }
    }
  }
  // 验证地磅编辑弹出层
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      carNumber: {
        validators: {
          notEmpty: {
            message: '请输入车牌号码'
          }
        }
      },
      uploadDate: {
        validators: {
          notEmpty: {
            message: '请输入称重过磅时间'
          }
        }
      }
    }
  }
  // 地磅编辑数据
  totalCount: any
  handleRow = {
    carNumber: '',
    deviceId: '',
    id: '',
    review: '',
    taskId: '',
    date: '',
    weight: ''
  }
  //分页回调
  paginate(e) {
    this.curPageTab = e.page + 1
    this.pageSizeTab = e.rows
    this.getTableDataTab('7')
  }
  // 地磅tab编辑
  editRow(row, val) {
    val.show()
    for (let item in this.handleRow) {
      this.handleRow[item] = row[item]
    }
    $('#rowDataForm').data('bootstrapValidator').resetForm()
  } //添加或者编辑的数据
  cancelEdit(val) {
    val.hide()
    $('#rowDataForm').data('bootstrapValidator').resetForm()
  }
  editSubmit(val) {
    $('#rowDataForm').bootstrapValidator('validate')
    let isValid = $('#rowDataForm').data('bootstrapValidator').isValid()
    if (isValid) {
      let reqdata = ''
      for (let item in this.handleRow) {
        if (item == 'carNumber') {
          reqdata += item + '=' + this.handleRow[item]
        } else {
          reqdata += '&' + item + '=' + this.handleRow[item]
        }
      }
      this.jsonApiService.http('weighbridge/updateWeighBridge.html', reqdata).subscribe(result => {
        this.jsonApiService.message(result.message)
        if (result.success) {
          this.getTableDataTab('7')
          this.cancelEdit(val)
        }
      })
    }
  }
  // 删除地磅数据
  deleteRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      var reqdata = 'ids=' + row.id
      this.jsonApiService.http('weighbridge/deleteBatch.html', reqdata).subscribe(result => {
        this.jsonApiService.message(result.message)
        this.getTableDataTab('7')
      })
    })
  }
  activeSelected: any //双击高亮行
  //待维修设备,双击刷新数据绘图
  waitRepairedRowSelect(row, type) {
    this.activeSelected = row.id
    switch (type) {
      case 'wait':
        if (!row.faultTime) {
          this.jsonApiService.message('该设备没有故障时间!')
          return
        }
        let temStartWait = common.mmsstoTimestamp(row.faultTime)
        this.startTime = row.faultTime
        this.endTime = common.getTimeMmss(new Date(temStartWait + 3 * 24 * 3600 * 1000))
        break
      case 'fixed':
        let temStartFixed = common.mmsstoTimestamp(row.repairedTime)
        this.startTime = common.getTimeMmss(new Date(temStartFixed - 1 * 24 * 3600 * 1000))
        this.endTime = common.getTimeMmss(new Date(temStartFixed + 2 * 24 * 3600 * 1000))
        break
      case 'question':
        this.startTime = row.startDate
        this.endTime = row.endDate
        break
      //			case 'alert':
      //				if(!row.offTime){
      //					this.jsonApiService.message('没有警报发生时间!');
      //					return;
      //				}
      //				let temStartAlert = new Date(row.offTime);
      //				this.startTime = row.offTime;
      //				this.endTime = row.onTime?row.onTime:common.getTimeMmss(new Date(temStartAlert.setDate(temStartAlert.getDate() + 3)));
      //				break;
      default:
        break
    }
    $('#datetimepicker1').val(this.startTime)
    $('#datetimepicker2').val(this.endTime)
    this.showChart()
  }
  // 标记设备状态打开的弹框的一些参数

  sensorSelectAll: any = {
    faultTypeName: '传感器问题',
    programType: '202',
    text: '传感器问题',
    selected: false
  }
  GPSSelectAll: any = {
    faultTypeName: 'GPS问题',
    programType: '203',
    text: 'GPS问题',
    selected: false
  }
  // 传感器的渲染数组
  sensorModuleList: any = []
  GPSProblemList = {
    startTime: '',
    endTime: '',
    operator: '',
    operatingTime: '',
    gpsProblem: '',
    selected: false
  }
  GPSModuleList: any = [
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '无GPS',
      code: 'GP1',
      selected: false
    },
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '停车速度平直',
      code: 'GP2',
      selected: false
    },
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '大段丢失',
      code: 'GP3',
      selected: false
    },
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '偶尔丢失',
      code: 'GP4',
      selected: false
    }
  ]
  // 初始化传感器和gps问题
  initSensorGps() {
    this.jsonApiService
      .http_obj('system/getDeviceBaseInfoByDeviceId.html', { deviceId: this.deviceId })
      .subscribe(result => {
        // 新增显示续费的信息 2020-10-12 张卓
        if (result.data.projectCarInfo) {
          this.renewalInfo = JSON.parse(JSON.stringify(result.data.projectCarInfo))
          // 过期判断
          if (this.renewalInfo.renewalDueTime) {
            let date = new Date()
            let now = date.getTime()
            let overlineDate = common.mmsstoTimestamp(this.renewalInfo.renewalDueTime)
            if (overlineDate > now) {
              this.renewalInfo.isOverDate = '未到期'
            } else {
              this.renewalInfo.isOverDate = '已到期'
            }
          }
        } else {
          this.renewalInfo = ''
        }
        //编辑设备信息 回显标记设备状态的标记 gps问题和编辑表单
        this.getEditDeviceInfo()
        this.haveRepaireObj = result.data.haveRepaired
        // 添加设备状态中的传感器的数据
        if (result.data.sensorChannel && result.data.sensorChannel.length > 0) {
          let temArr: any = []
          for (var j = 0; j < result.data.sensorChannel.length; j++) {
            let obj = {
              value: result.data.sensorChannel[j],
              flag: false,
              isFront: '0'
            }
            if (result.data.coef) {
              if (result.data.coef[+result.data.sensorChannel[j] - 1]) {
                obj.flag = true
              }
            }
            if (result.data.sensorAxle && result.data.sensorAxle.length > 0) {
              obj.isFront = result.data.sensorAxle[j]
            }
            //					if(result.data.sensorAxle.length == result.data.sensorChannel.length){
            //						obj.isFront= result.data.sensorAxle[j]
            //					}
            temArr.push(obj)
          }
          result.data.sensorChannel = temArr
          this.loadSensorModule(result.data.sensorChannel)
        } else {
          this.loadSensorModule([])
        }
        this.deviceOffline.selected = false
        this.deviceContact.selected = false
        this.deviceRepairedIspush.selected = false
      })
  }
  //加载传感器数据
  loadSensorModule(data) {
    this.sensorModuleList = []
    for (let item of data) {
      let obj = {
        flag: item.flag,
        value: item.value,
        text: '传感器' + item.value,
        faultTypeName: '传感器问题',
        programType: '202',
        startTime: '',
        endTime: '',
        operator: '',
        operatingTime: '',
        sensorProblem: '',
        selected: false,
        isFront: item.isFront,
        child: [
          {
            text: '正负52万',
            code: 'SP1',
            selected: false
          },
          {
            text: '偶尔52万',
            code: 'SP1-1',
            selected: false
          },
          {
            text: '经常52万',
            code: 'SP1-2',
            selected: false
          },
          {
            text: '乱跳',
            code: 'SP2',
            selected: false
          },
          {
            text: '形变小',
            code: 'SP3',
            selected: false
          },
          {
            text: '方向反',
            code: 'SP4',
            selected: false
          },
          {
            text: '平直',
            code: 'SP5',
            selected: false
          }
        ]
      }
      this.sensorModuleList.push(obj)
    }
  }
  // 标记设备状态打开的弹框
  sensorSelectAllClick() {
    this.sensorSelectAll.selected = !this.sensorSelectAll.selected
  }
  //
  vIconQ: string = '0'
  isShowQuestion: boolean = true
  // 点击标记设备状态按钮
  deviceStatusChange() {
    if (!this.deviceStatus) {
      $('#chart').width('62%')
      $('#deviceStatusModuleBox').css('display', 'block')
      $(window).trigger('resize')
      this.deviceStatus = true
    } else {
      $('#chart').width('100%')
      //			$('#chart').children("div").width("100%")
      //			$('#chart').children("div").children("canvas").width("100%")
      $('#deviceStatusModuleBox').css('display', 'none')
      $(window).trigger('resize')
      this.deviceStatus = false
    }
  }
  // 传感器选择的
  sensorLisSelected(id, code) {
    for (let item of this.sensorModuleList) {
      if (item.value == id) {
        for (let lis of item.child) {
          if (lis.code == code) {
            lis.selected = !lis.selected
          } else {
            lis.selected = false
          }
        }
      }
    }
    this.sensorSelectAll.selected = false
    for (let item of this.sensorModuleList) {
      for (let lis of item.child) {
        if (lis.selected) {
          this.sensorSelectAll.selected = true
          break
        }
      }
    }
  }
  // 主机全选框
  hostAllSelect: boolean = false
  hostSelectAllClick(type?) {
    // 目前没有全选功能
    if (type) {
      this.hostAllSelect = !this.hostAllSelect
    } else {
      this.hostAllSelect = false
      if (this.deviceOffline.selected || this.deviceContact.selected || this.distrustThrow.selected) {
        this.hostAllSelect = true
      }
    }
  }
  // 其他大类全选框
  otherAllSelect: boolean = false
  otherSelectAllClick(type?) {
    // 目前没有全选功能
    if (type) {
      this.otherAllSelect = !this.otherAllSelect
    } else {
      this.deviceOther.selected ? this.otherAllSelect = true : this.otherAllSelect = false
    }
  }
  // GPS全选框
  GPSSelectAllClick() {
    this.GPSSelectAll.selected = !this.GPSSelectAll.selected
  }
  // GPS列表选择
  GPSLisSelected(code) {
    for (let lis of this.GPSModuleList) {
      if (lis.code == code) {
        lis.selected = !lis.selected
        lis.selected ? (this.GPSSelectAll.selected = true) : (this.GPSSelectAll.selected = false)
      } else {
        lis.selected = false
      }
    }
  }
  // 传感器全部平直,更新至车辆管理表
  // isAllStraight: boolean = false
  // allSensorKeepValue() {
  //   this.isAllStraight = !this.isAllStraight
  // }
  //更新设备状态
  updataDeviceStatus() {
    let sensorProblem: string = '',
      gpsProblem: string = '',
      sensorFlag: any,
      gpsFlag: any
    for (let item of this.sensorModuleList) {
      for (let lis of item.child) {
        if (lis.selected) {
          if (sensorProblem) {
            sensorProblem += ',' + item.text + '-' + lis.text
          } else {
            sensorProblem += item.text + '-' + lis.text
          }
        }
      }
    }
    for (let item of this.GPSModuleList) {
      if (item.selected) {
        gpsProblem = item.text
      }
    }
    if (this.sensorSelectAll.selected) {
      sensorFlag = 1
    } else {
      sensorFlag = 0
    }
    if (this.GPSSelectAll.selected) {
      gpsFlag = 1
    } else {
      gpsFlag = 0
    }
    if (!this.deviceId) {
      this.jsonApiService.message('请选择设备')
      return
    }
    // if (!sensorFlag && !gpsFlag && !this.isAllStraight) {
    //   this.jsonApiService.message('请选择问题分类')
    //   return
    // }
    if (!sensorFlag && !gpsFlag) {
      this.jsonApiService.message('请选择问题分类')
      return
    }
    this.jsonApiService.confirm_message('您确定要更新设备状态？').then(() => {
      let reqdata = {
        // isAllStraight: this.isAllStraight ? 1 : 0,
        sensor: sensorFlag,
        gps: gpsFlag,
        deviceId: this.deviceId,
        sensorProblem: sensorProblem,
        gpsProblem: gpsProblem,
        startDate: $('#datetimepicker1').val(),
        endDate: $('#datetimepicker2').val()
      }
      this.jsonApiService.http_obj('car/updateCarStatus.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.getEditDeviceInfo()
        }
      })
    })
  }
  page: any = {
    id: '',
    companyId: '',
    carNumber: '',
    deviceId: '',
    useTypeL1: '',
    useTypeL2: '',
    sensorType: '2',
    sensorAmount: '',
    sensorChannel: [],
    carAxleAmount: '',
    gpsAntenna: '',
    gsmAntenna: '',
    phone: '',
    driverName: '',
    sensorAxle: [], //传感器通道
    sensorPosition: [] //安装位置
  }
  deviceSensorArr: any = [
    {
      id: 1,
      text: '通道1',
      checked: false
    },
    {
      id: 2,
      text: '通道2',
      checked: false
    },
    {
      id: 3,
      text: '通道3',
      checked: false
    },
    {
      id: 4,
      text: '通道4',
      checked: false
    },
    {
      id: 5,
      text: '通道5',
      checked: false
    },
    {
      id: 6,
      text: '通道6',
      checked: false
    },
    {
      id: 7,
      text: '通道7',
      checked: false
    },
    {
      id: 8,
      text: '通道8',
      checked: false
    },
    {
      id: 9,
      text: '通道9',
      checked: false
    },
    {
      id: 10,
      text: '通道10',
      checked: false
    },
    {
      id: 11,
      text: '通道11',
      checked: false
    },
    {
      id: 12,
      text: '通道12',
      checked: false
    },
    {
      id: 13,
      text: '通道13',
      checked: false
    },
    {
      id: 14,
      text: '通道14',
      checked: false
    },
    {
      id: 15,
      text: '通道15',
      checked: false
    },
    {
      id: 16,
      text: '通道16',
      checked: false
    }
  ]
  // 编辑页面的数据
  carTypeList = carTypeListObj.carTypeList
  // 打开编辑窗口
  editDeviceInfo(modal) {
    if (!this.deviceId) {
      this.jsonApiService.message('请选择设备')
      return
    }
    modal.show()
    this.getEditDeviceInfo()
  }
  //请求传感器类型的接口
  querySensor() {
    this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe(data => {
      if (data.success) {
        this.inputParam = data.data
      }
    })
  }
  inputParam: any = []
  //传感器类型change回调
  sensorTypeChange(val) {
    this.page.sensorType = val
  }
  sensorSelected(data) {
    this.page.sensorType = data.sensorType
  }
  //gps天线change回调
  gpsAntennaChange(val) {
    this.page.gpsAntenna = val
    // if (this.page.gsmAntenna != val) {
    // 	this.gsmAntennaChange(val);
    // }
    for (var i = 0; i < allSelectOptionsObj.gsmOptions.length; i++) {
      if (allSelectOptionsObj.gsmOptions[i].text == val) {
        this.page.gsmAntenna = val
      }
    }
  }
  //gsm天线change回调
  gsmAntennaChange(val) {
    this.page.gsmAntenna = val
    // if (this.page.gpsAntenna != val) {
    // 	this.gpsAntennaChange(val);
    // }
    for (var i = 0; i < allSelectOptionsObj.gpsOptions.length; i++) {
      if (allSelectOptionsObj.gpsOptions[i].text == val) {
        this.page.gpsAntenna = val
      }
    }
  }
  //全局请求 天线配置接口 GPS天线/GSM天线
  getGpsInfo() {
    this.jsonApiService.http('gpsAntenna/getGpsInfo.html', '').subscribe(data => {
      if (data.success) {
        var obj
        allSelectOptionsObj.gpsOptions = []
        allSelectOptionsObj.gsmOptions = []
        for (var i = 0; i < data.data.length; i++) {
          if (data.data[i].type == 'GPS天线') {
            obj = {
              value: data.data[i].antennaName,
              text: data.data[i].antennaName
            }
            allSelectOptionsObj.gpsOptions.push(obj)
          } else if (data.data[i].type == 'GSM天线') {
            obj = {
              value: data.data[i].antennaName,
              text: data.data[i].antennaName
            }
            allSelectOptionsObj.gsmOptions.push(obj)
          }
        }
        this.gpsOptions = allSelectOptionsObj.gpsOptions
        this.gsmOptions = allSelectOptionsObj.gsmOptions
      }
    })
  }
  // 传感器选择框
  deviceSensorChange(id, e) {
    // this.page.sensorChannel = [];
    // if(e.target.checked){
    // 	this.deviceSensorArr[id-1].checked = true;
    // }else{
    // 	this.deviceSensorArr[id-1].checked = false;
    // }
    // for(let item of this.deviceSensorArr){
    // 	if(item.checked){
    // 		this.page.sensorChannel.push(item.id);
    // 	}
    // }
    // this.page.sensorAmount = this.page.sensorChannel.length||'';

    var sensorAxleList = []
    this.page.sensorChannel = []
    let sensor
    var listFront = JSON.parse(JSON.stringify(this.sensorAxleFront))
    var listAfter = JSON.parse(JSON.stringify(this.sensorAxleAfter))
    var listChannel = JSON.parse(JSON.stringify(this.checkChannel))
    var that = this

    if (e.target.checked) {
      that.deviceSensorArr[id - 1].checked = true
      sensor = {
        mark: id,
        text: id,
        checked: false,
        isDisable: false
      }
      listFront.push(sensor)
      listAfter.push(sensor)
      listChannel.push(sensor)
      that.sensorAxleFront = that.deepClone(listFront)
      that.sensorAxleAfter = that.deepClone(listAfter)
      that.checkChannel = that.deepClone(listChannel)
      // that.sensorAxleAfter = that.deepClone(that.sensorAxleFront);
      // that.checkChannel = that.deepClone(that.sensorAxleFront);

      that.sensorAxleFront.sort(that.compare('mark'))
      that.sensorAxleAfter.sort(that.compare('mark'))
      that.checkChannel.sort(that.compare('mark'))
    } else {
      that.deviceSensorArr[id - 1].checked = false
      if (that.sensorAxleFront.length != 0) {
        for (let i = 0; i < that.sensorAxleFront.length; i++) {
          if (that.sensorAxleFront[i].mark == id) {
            listFront.splice(i, 1)
            listAfter.splice(i, 1)
            listChannel.splice(i, 1)
            this.clear(id)
            that.sensorAxleFront = that.deepClone(listFront)
            that.sensorAxleAfter = that.deepClone(listAfter)
            that.checkChannel = that.deepClone(listChannel)

            // that.sensorAxleAfter = that.deepClone(that.sensorAxleFront);
            // that.checkChannel = that.deepClone(that.sensorAxleFront);
          }
        }
      }
    }
    for (let item of this.deviceSensorArr) {
      if (item.checked) {
        this.page.sensorChannel.push(item.id)
      }
    }
    this.page.sensorAmount = this.page.sensorChannel.length || ''

    for (let j = 0; j < this.sensorAxleAfter.length; j++) {
      if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
        sensorAxleList.push(0)
      } else if (this.sensorAxleAfter[j].checked) {
        sensorAxleList.push(2)
      } else if (this.sensorAxleAfter[j].isDisable) {
        sensorAxleList.push(1)
      }
    }
    this.page.sensorAxle = this.deepClone(sensorAxleList)

    this.showCheck(that.checkChannel)
  }
  // 关闭编辑窗口
  closeEditDeciceModal(modal) {
    modal.hide()
  }
  // [传感器待维修, GPS待维修, 主机待维修, 其他待维修]
  faultProblemResults = [null, null, null, null]
  // 编辑设备信息
  getEditDeviceInfo() {
    this.jsonApiService.http_obj('car/getCarInfoByDeviceId.html', { deviceId: this.deviceId }).subscribe(data => {
      if (data.success) {
        this.clearEditDeviceInfo()
        const result = data.data
        // this.isAllStraight = result.isAllStraight ? true : false
        this.faultProblemResults = result.faultProblemResults.map(item => ({
          ...item,
          id: item.linkWaitRepairRecordId,
          isPush: item.limitEnterFactoryCode
        }))

        for (let item in this.page) {
          if (item == 'sensorChannel' && !result[item]) {
            result[item] = []
          }
          this.page[item] = result[item]
        }
        let resultChannel = []
        if (result.sensorChannel) {
          for (let item of result.sensorChannel) {
            if (item && item !== 'null') {
              resultChannel.push(item)
            }
          }
          result.sensorChannel = resultChannel
        }
        for (let item of this.deviceSensorArr) {
          item.checked = false
        }
        if (result.sensorChannel.length > 0) {
          for (var i = 0; i < result.sensorChannel.length; i++) {
            this.deviceSensorArr[result.sensorChannel[i] - 1].checked = true
          }
        }
        if (result.sensorProblemList) {
          if (result.sensorProblemList.length > 0) {
            //                      this.sensorSelectAll.selected = true;
            for (let sensor of result.sensorProblemList) {
              let sensorItem = sensor.sensorProblem.split('-')
              for (let item of this.sensorModuleList) {
                if (item.text == sensorItem[0]) {
                  item.startTime = sensor.startTime
                  item.endTime = sensor.endTime
                  item.operator = sensor.operator
                  item.operatingTime = sensor.operatingTime
                  item.sensorProblem = sensor.sensorProblem
                  for (let lis of item.child) {
                    if (lis.text == sensorItem[1]) {
                      lis.selected = true
                      item.selected = true
                    } else {
                      lis.selected = false
                    }
                  }
                }
              }
            }
          }
        }
        if (result.gpsProblemEntity) {
          let gps = result.gpsProblemEntity
          this.GPSProblemList.startTime = gps.startTime
          this.GPSProblemList.endTime = gps.endTime
          this.GPSProblemList.operator = gps.operator
          this.GPSProblemList.operatingTime = gps.operatingTime
          this.GPSProblemList.gpsProblem = gps.gpsProblem
          for (let item of this.GPSModuleList) {
            if (item.text == gps.gpsProblem) {
              item.selected = true
              this.GPSProblemList.selected = true
            } else {
              item.selected = false
            }
          }
        }
        $('#useTypeSelect').val(this.page.useTypeL2).trigger('change')

        this.ChannelLen = data.data.carAxleAmount
        //选中通道值
        this.showLocation(data.data.sensorChannel, data.data.sensorPosition, data.data.carAxleAmount)

        let sensor1, sensor2
        this.sensorAxleFront = []
        this.sensorAxleAfter = []
        var AxleFrontList = JSON.parse(JSON.stringify(this.sensorAxleFront))
        var AxleAfterList = JSON.parse(JSON.stringify(this.sensorAxleAfter))
        // this.sensorAxleAfter = this.deepClone(this.sensorAxleFront); //深拷贝

        for (let j = 0; j < data.data.sensorChannel.length; j++) {
          if (data.data.sensorAxle == null || data.data.sensorAxle.length == 0) {
            sensor1 = {
              mark: data.data.sensorChannel[j],
              text: data.data.sensorChannel[j],
              checked: false,
              isDisable: false
            }

            AxleFrontList.push(sensor1)
            AxleAfterList.push(sensor1)
          } else {
            for (let k = 0; k < data.data.sensorAxle.length; k++) {
              if (data.data.sensorAxle[k] == 0 && k == j) {
                sensor1 = {
                  mark: data.data.sensorChannel[j],
                  text: data.data.sensorChannel[j],
                  checked: false,
                  isDisable: false
                }
                AxleFrontList.push(sensor1)
                AxleAfterList.push(sensor1)
              } else if (data.data.sensorAxle[k] == 1 && k == j) {
                sensor1 = {
                  mark: data.data.sensorChannel[j],
                  text: data.data.sensorChannel[j],
                  checked: true,
                  isDisable: false
                }
                sensor2 = {
                  mark: data.data.sensorChannel[j],
                  text: data.data.sensorChannel[j],
                  checked: false,
                  isDisable: true
                }
                AxleFrontList.push(sensor1)
                AxleAfterList.push(sensor2)
              } else if (data.data.sensorAxle[k] == 2 && k == j) {
                sensor1 = {
                  mark: data.data.sensorChannel[j],
                  text: data.data.sensorChannel[j],
                  checked: false,
                  isDisable: true
                }
                sensor2 = {
                  mark: data.data.sensorChannel[j],
                  text: data.data.sensorChannel[j],
                  checked: true,
                  isDisable: false
                }
                AxleFrontList.push(sensor1)
                AxleAfterList.push(sensor2)
              }
            }
          }
          this.sensorAxleFront = this.deepClone(AxleFrontList) //深拷贝
          this.sensorAxleAfter = this.deepClone(AxleAfterList) //深拷贝
        }
      } else {
        this.jsonApiService.message(data.message)
      }
    })

    //算法问题清空
    for (let lis of this.algorithmQuestionList) {
      lis.selected = false
    }
  }
  // 清空编辑设备信息表
  clearEditDeviceInfo() {
    this.faultProblemResults = [null, null, null, null]
    this.GPSSelectAll.selected = false
    this.sensorSelectAll.selected = false
    this.hostAllSelect = false
    this.otherAllSelect = false
    for (let item in this.page) {
      this.page[item] = ''
      if (item == 'sensorChannel') {
        this.page[item] = []
      }
    }
    for (let item of this.GPSModuleList) {
      item.selected = false
    }
    for (let item of this.sensorModuleList) {
      item.startTime = ''
      item.endTime = ''
      item.operator = ''
      item.operatingTime = ''
      item.sensorProblem = ''
      for (let lis of item.child) {
        lis.selected = false
      }
    }
    for (let item of this.deviceSensorArr) {
      item.checked = false
    }
    this.GPSProblemList = {
      startTime: '',
      endTime: '',
      operator: '',
      operatingTime: '',
      gpsProblem: '',
      selected: false
    }
    // 重置表单的数据
    $('#sensorAmount').val('')
    $('#useTypeSelect').val(null).trigger('change')
  }
  // 提交表单数据
  submitEditDeciceModal(modal) {
    var reqdata = new FormData()
    this.page.useTypeL2 = $('#useTypeSelect').val()
    this.page.useTypeL1 = $('#useTypeSelect').val().slice(0, 2)
    if (this.page.sensorChannel) {
      for (let iems of this.page.sensorChannel) {
        if (!iems) iems = ''
      }
    } else {
      this.page.sensorChannel = []
    }
    if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
      if (this.sensorAxleAfter.length != 0) {
        let sensorAxleList = []
        for (let j = 0; j < this.sensorAxleAfter.length; j++) {
          sensorAxleList.push(0)
        }
        this.page.sensorAxle = this.deepClone(sensorAxleList)
      }
    }
    // if(!$('#sensorAmount').val()){
    // 	this.page.sensorAmount = ""
    // }

    for (let item in this.page) {
      if (item == 'sensorPosition') {
        this.page.sensorPosition = this.filterPosition(this.installArray)
        reqdata.append('sensorPositionJson', JSON.stringify(this.page.sensorPosition))
      } else {
        reqdata.append(item, common.stringTrim(this.page[item]))
      }
    }
    this.jsonApiService.form_http('car/edit.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.getEditDeviceInfo()
        this.initSensorGps()
        // this.initOrderDeviceModal(this.activeSelected)
        modal.hide()
      }
    })
  }
  // 离线
  deviceOffline: any = {
    faultTypeName: '主机问题',
    programType: '201',
    text: '离线',
    selected: false
  }
  // 接电问题
  deviceContact: any = {
    faultTypeName: '主机问题',
    programType: '201',
    text: '接电问题',
    selected: false
  }
  distrustThrow: any = {
    text: '疑似甩挂',
    selected: false
  }
  // 限制进厂
  deviceRepairedIspush: any = {
    text: '限制进厂',
    selected: false
  }
  // 硬件问题的其他选项
  deviceOther: any = {
    text: '其他',
    faultTypeName: '其他',
    programType: '200',
    selected: false
  }
  // 硬件问题的其他的问题描述
  hardwareIssueDescription = ''
  deviceOfflineClick() {
    this.deviceOffline.selected = !this.deviceOffline.selected
    this.hostSelectAllClick()
  }
  deviceContactClick() {
    this.deviceContact.selected = !this.deviceContact.selected
    this.hostSelectAllClick()
  }
  distrustThrowClick() {
    this.distrustThrow.selected = !this.distrustThrow.selected
    this.hostSelectAllClick()
  }
  deviceRepairedIspushClick() {
    this.deviceRepairedIspush.selected = !this.deviceRepairedIspush.selected
  }
  deviceOtherClick() {
    this.deviceOther.selected = !this.deviceOther.selected
    if (!this.deviceOther.selected) {
      this.hardwareIssueDescription = ''
    }
    this.otherSelectAllClick()
  }
  //添加设备维修
  addDeviceRepaired() {
    let data: any = []
    let sensorProblem: string = '',
      gpsProblem: string = '',
      sensorFlag: any,
      gpsFlag: any
    if (this.sensorSelectAll.selected) {
      sensorFlag = 1
      for (let item of this.sensorModuleList) {
        for (let lis of item.child) {
          if (lis.selected) {
            if (sensorProblem) {
              sensorProblem += ',' + item.text + '-' + lis.text
            } else {
              sensorProblem += item.text + '-' + lis.text
            }
          }
        }
      }
    } else {
      sensorFlag = 0
    }
    if (this.GPSSelectAll.selected) {
      gpsFlag = 1
      for (let item of this.GPSModuleList) {
        if (item.selected) {
          gpsProblem = item.text
        }
      }
    } else {
      gpsFlag = 0
    }
    if (sensorProblem) {
      let sensorObj = {
        programType: '202',
        deviceId: this.deviceId,
        carNumber: this.carNumber,
        faultTypeName: '传感器问题',
        faultTime: this.startTime,
        faultPhenomenon: sensorProblem.split(','),
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      data.push(sensorObj)
    }
    if (gpsProblem) {
      let gpsObj = {
        programType: '203',
        deviceId: this.deviceId,
        carNumber: this.carNumber,
        faultTypeName: 'GPS问题',
        faultTime: this.startTime,
        faultPhenomenon: gpsProblem.split(','),
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      data.push(gpsObj)
    }
    // 因为离线和接电问题是同一种类型的问题，所以在这里进行合并处理 faultPhenomenon: ['离线', '接电问题']
    if (this.hostAllSelect && (this.deviceOffline.selected || this.deviceContact.selected || this.distrustThrow.selected)) {
      const offlineObj = {
        programType: this.deviceOffline.programType,
        deviceId: this.deviceId,
        carNumber: this.carNumber,
        faultTypeName: '主机问题',
        faultTime: this.startTime,
        // faultPhenomenon: this.deviceOffline.text.split(','),
        faultPhenomenon: [],
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      if (this.deviceOffline.selected) {
        offlineObj.faultPhenomenon.push(this.deviceOffline.text)
      }
      if (this.deviceContact.selected) {
        offlineObj.faultPhenomenon.push(this.deviceContact.text)
      }
      if (this.distrustThrow.selected) {
        offlineObj.faultPhenomenon.push(this.distrustThrow.text)
      }
      // if (this.deviceRepairedIspush.selected) {
      //   offlineObj.faultPhenomenon.push(this.deviceRepairedIspush.text)
      // }
      // 其他
      // if (this.deviceOther.selected) {
      //   offlineObj.faultPhenomenon.push(this.hardwareIssueDescription?this.hardwareIssueDescription:this.deviceOther.text)
      // }
      data.push(offlineObj)
    }
    // 其他
    if (this.otherAllSelect && this.deviceOther.selected) {
      let deviceOtherObj = {
        programType: this.deviceOther.programType,
        deviceId: this.deviceId,
        carNumber: this.carNumber,
        faultTypeName: '其他',
        faultTime: this.startTime,
        faultPhenomenon: this.hardwareIssueDescription.split(';;;'), // 形成一个数组
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      data.push(deviceOtherObj)
    }
    if (
      !sensorProblem &&
      !gpsProblem &&
      !(this.hostAllSelect && (this.deviceOffline.selected || this.deviceContact.selected || this.distrustThrow.selected)) &&
      !(this.otherAllSelect && this.deviceOther.selected)
    ) {
      this.jsonApiService.message('请选择故障类型')
      return
    }
    let reqdata = 'list=' + JSON.stringify(data) + '&sensor=' + sensorFlag + '&gps=' + gpsFlag
    // 限制车辆的“开始时间” 要小于“ 维修时间”，做个弹框，提示内容：“ 粤B33322 于[xxxx-xx-xx xx:xx:xx]已维修，请与[xxx]（维修人） 核实维修情况 ”，是，继续录入维修，否，取消该次操作
    let selectTime = new Date($('#datetimepicker1').val()).getTime()
    let lastServiceTime = this.haveRepaireObj ? this.haveRepaireObj.repairedTime : null
    let lastTime = new Date(lastServiceTime).getTime()
    // 点击了限制进厂 并且 选择的时间小于最后一次维修的时间 就进行提示
    if (this.deviceRepairedIspush.selected && selectTime < lastTime) {
      let carNumber = this.haveRepaireObj.carNumber
      let repairedUser = this.haveRepaireObj.repairedUserName
      // 提示
      this.notificationService.smartMessageBox(
        {
          title: '提示',
          content: carNumber + '于 [' + lastServiceTime + '] 已维修，请与 [' + repairedUser + ']（维修人）核实维修情况',
          buttons: '[继续录入][取消]'
        },
        ButtonPressed => {
          if (ButtonPressed === '继续录入') {
            // 继续录入就直接录入
            this.jsonApiService.http('deviceRepaired/insertDeviceRepairedBatch.html', reqdata).subscribe(data => {
              this.jsonApiService.message(data.message)
            })
          }
          if (ButtonPressed === '取消') {
            // this.notificationService.smallBox({
            // 	content: "操作取消",
            // 	timeout: 3000
            // });
            return
          }
        }
      )
    } else {
      this.jsonApiService.http('deviceRepaired/validateRecord.html', 'deviceId=' + this.deviceId).subscribe(result => {
        if (result.valid) {
          this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
            this.jsonApiService.http('deviceRepaired/insertDeviceRepairedBatch.html', reqdata).subscribe(data => {
              this.jsonApiService.message(data.message)
            })
          })
        } else {
          this.jsonApiService.http('deviceRepaired/insertDeviceRepairedBatch.html', reqdata).subscribe(data => {
            this.jsonApiService.message(data.message)
          })
        }
      })
    }
    // this.jsonApiService.http('deviceRepaired/validateRecord.html', 'deviceId=' + this.deviceId).subscribe(result => {
    // 	if(result.valid) {
    // 		this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
    // 			this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
    // 				this.jsonApiService.message(data.message);
    // 			})
    // 		})
    // 	} else {
    // 		this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
    // 			this.jsonApiService.message(data.message);
    // 		})
    // 	}
    // })
  }
  // 提交传感器问题,单个传感器
  updateSensorProblem(item) {
    let sensorProblem: string = ''
    for (let lis of item.child) {
      if (lis.selected) {
        sensorProblem = item.text + '-' + lis.text
      }
    }
    if (!sensorProblem) {
      this.jsonApiService.message('请选择传感器问题')
      return
    }
    let reqdata = {
      deviceId: this.deviceId,
      index: item.value - 1,
      startTime: $('#datetimepicker1').val(),
      endTime: $('#datetimepicker2').val(),
      sensorProblem: sensorProblem
    }
    this.jsonApiService.http_obj('car/updateSensorProblem.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.getEditDeviceInfo()
      }
    })
  }
  // 提交GPS问题,单个GPS
  updateGPSProblem() {
    let gpsProblem: string = ''
    for (let item of this.GPSModuleList) {
      if (item.selected) {
        gpsProblem = item.text
      }
    }
    if (!gpsProblem) {
      this.jsonApiService.message('请选择GPS问题')
      return
    }
    let reqdata = {
      deviceId: this.deviceId,
      startTime: $('#datetimepicker1').val(),
      endTime: $('#datetimepicker2').val(),
      gpsProblem: gpsProblem
    }
    this.jsonApiService.http_obj('car/updateGpsProblem.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.getEditDeviceInfo()
      }
    })
  }
  // 问题区间数据查看,查看问题区间重量曲线图
  dataDrawEchartBMap(item) {
    let queryParams = {
      deviceId: this.deviceId,
      carNumber: this.carNumber,
      startDate: item.startTime,
      endDate: item.endTime
    }
    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('jumpFromOrderManagenment', JSON.stringify(queryParams))
    window.open(BaseURL + '#/system-config/data-optimization')
    //      $('#echartMapModal').show();
    //      this.echartParam = {
    //          deviceId: this.deviceId,
    //          carNumber: this.carNumber,
    //          startTime: item.startTime,
    //          endTime: item.endTime,
    //          coefficient: this.deviceBaseInfo.coef
    //      }
  }
  closeEchartMapModal() {
    $('#echartMapModal').hide()
  }

  /**
   *  曲线图查看
   */
  drawTrackList: any
  echartParam: any
  isShowMapView: boolean = false //默认不显示地图轨迹
  //获取到绘制轨迹数据,传递给地图组件
  initMapDate(value) {
    this.drawTrackList = value
  }
  // 是否显示地图
  isHasMapView(val) {
    this.isShowMapView = val
  }

  /* 传感器通道 前轴 后轴  通道 */

  //通道 前
  sensorAxleFrontChange(item, e) {
    let sensorAxleList = []
    for (let i = 0; i < this.sensorAxleFront.length; i++) {
      if (item.mark == this.sensorAxleFront[i].mark) {
        if (e.target.className.indexOf('wayCheck') != -1) {
          this.sensorAxleFront[i].checked = false
          this.sensorAxleAfter[i].isDisable = false
        } else {
          this.sensorAxleFront[i].checked = true
          this.sensorAxleAfter[i].isDisable = true
        }
      }
    }

    for (let j = 0; j < this.sensorAxleAfter.length; j++) {
      if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
        sensorAxleList.push(0)
      } else if (this.sensorAxleAfter[j].checked) {
        sensorAxleList.push(2)
      } else if (this.sensorAxleAfter[j].isDisable) {
        sensorAxleList.push(1)
      }
    }
    this.page.sensorAxle = this.deepClone(sensorAxleList)
  }
  //深拷贝浅拷贝
  deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  }
  //通道 后
  sensorAxleAfterChange(item, e) {
    let sensorAxleList = []
    for (let i = 0; i < this.sensorAxleAfter.length; i++) {
      if (item.mark == this.sensorAxleAfter[i].mark) {
        if (e.target.className.indexOf('wayCheck') != -1) {
          this.sensorAxleAfter[i].checked = false
          this.sensorAxleFront[i].isDisable = false
        } else {
          this.sensorAxleAfter[i].checked = true
          this.sensorAxleFront[i].isDisable = true
        }
      }
    }

    for (let j = 0; j < this.sensorAxleFront.length; j++) {
      if (!this.sensorAxleFront[j].checked && !this.sensorAxleFront[j].isDisable) {
        sensorAxleList.push(0)
      } else if (this.sensorAxleFront[j].checked) {
        sensorAxleList.push(1)
      } else if (this.sensorAxleFront[j].isDisable) {
        sensorAxleList.push(2)
      }
    }
    this.page.sensorAxle = this.deepClone(sensorAxleList)
  }
  //过滤通道数据
  filterPosition(value) {
    var List = []
    var ListParant = []
    this.page.sensorPosition = []
    for (let j = 0; j < value.length; j++) {
      if (
        value[j].positionLMR[0].sensorChannel.length != 0 &&
        value[j].positionLMR[1].sensorChannel.length != 0 &&
        value[j].positionLMR[2].sensorChannel.length != 0
      ) {
        List.push(value[j])
      } else {
        for (let a = 0; a < value[j].positionLMR.length; a++) {
          if (value[j].positionLMR[a].sensorChannel.length != 0) {
            ListParant.push(value[j].positionLMR[a])
          }
        }
        if (ListParant.length != 0) {
          var positionLMR = {
            index: j + 1,
            positionLMR: ListParant
          }
          List.push(positionLMR)
        }

        // if(ListParant.length != 0){List.push(ListParant);}
        ListParant = []
        continue
      }
    }
    return List
  }
  //显示安装位置
  showLocation(sensorChannel, value, Lens) {
    var installArray = [
      {
        index: 1,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 2,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 3,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 4,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 5,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 6,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      }
    ] //安装位置
    let sensor
    let array = []
    this.checkChannel = []
    if (sensorChannel != 0) {
      for (let i = 0; i < sensorChannel.length; i++) {
        sensor = {
          mark: sensorChannel[i],
          text: sensorChannel[i],
          checked: false,
          isDisable: false
        }
        this.checkChannel.push(sensor)
        this.checkChannel.sort(this.compare('mark'))
        var checkChannelList = JSON.parse(JSON.stringify(this.checkChannel))
      }
    }
    var len
    if (value != null && value.length != 0) {
      len = value[value.length - 1].index
    } else {
      if (Lens == '') {
        Lens = 0
      }
      len = Lens
    }
    if (value != 0 && value != null) {
      for (let j = 0; j < installArray.length; j++) {
        for (let k = 0; k < value.length; k++) {
          if (installArray[j].index == value[k].index) {
            for (let f = 0; f < value[k].positionLMR.length; f++) {
              if (value[k].positionLMR[f].position == 'L') {
                installArray[j].positionLMR[0].sensorChannel = value[k].positionLMR[f].sensorChannel
                continue
              }
              if (value[k].positionLMR[f].position == 'M') {
                installArray[j].positionLMR[1].sensorChannel = value[k].positionLMR[f].sensorChannel
                continue
              }
              if (value[k].positionLMR[f].position == 'R') {
                installArray[j].positionLMR[2].sensorChannel = value[k].positionLMR[f].sensorChannel
                continue
              }
            }
            break
          }
        }
      }
      if (len > Lens || len == Lens) {
        if (len != 0) {
          installArray.splice(len, 6 - len)
        }
      } else {
        if (len != 0) {
          installArray.splice(Lens, 6 - Lens)
        }
      }

      this.installArray = this.deepClone(installArray)
    } else {
      if (len != 0) {
        installArray.splice(len, 6 - len)
      }
      this.installArray = this.deepClone(installArray)
    }

    this.showCheck(this.checkChannel)
  }
  compare(property) {
    return function (a, b) {
      var value1 = a[property]
      var value2 = b[property]
      return value1 - value2
    }
  }
  showCheck(value) {
    var showCheckList = []
    for (var a = 0; a < this.installArray.length; a++) {
      for (var b = 0; b < this.installArray[a].positionLMR.length; b++) {
        for (var c = 0; c < this.installArray[a].positionLMR[b].sensorChannel.length; c++) {
          showCheckList.push(this.installArray[a].positionLMR[b].sensorChannel[c])
        }
      }
    }

    for (var i = 0; i < value.length; i++) {
      for (var j = 0; j < showCheckList.length; j++) {
        if (value[i].mark == showCheckList[j]) {
          value[i].isDisable = true
          break
        }
      }
    }

    this.checkChannel = this.deepClone(value)
  }
  clear(value) {
    for (let j = 0; j < this.installArray.length; j++) {
      var sensorChannelL = this.installArray[j].positionLMR[0].sensorChannel
      var sensorChannelM = this.installArray[j].positionLMR[1].sensorChannel
      var sensorChannelR = this.installArray[j].positionLMR[2].sensorChannel
      for (var k = 0; k < sensorChannelL.length; k++) {
        if (sensorChannelL[k] == value) {
          sensorChannelL.splice(k, 1)
        }
        this.installArray[j].positionLMR[0].sensorChannel = this.deepClone(sensorChannelL)
        this.installArray[j].positionLMR[0].sensorChannel.sort(this.sortNumber)
      }
      for (var h = 0; h < sensorChannelM.length; h++) {
        if (sensorChannelM[h] == value) {
          sensorChannelM.splice(h, 1)
        }
        this.installArray[j].positionLMR[1].sensorChannel = this.deepClone(sensorChannelM)
        this.installArray[j].positionLMR[1].sensorChannel.sort(this.sortNumber)
      }
      for (var f = 0; f < sensorChannelR.length; f++) {
        if (sensorChannelR[f] == value) {
          sensorChannelR.splice(f, 1)
        }
        this.installArray[j].positionLMR[2].sensorChannel = this.deepClone(sensorChannelR)
        this.installArray[j].positionLMR[2].sensorChannel.sort(this.sortNumber)
      }
    }

    this.page.sensorPosition = this.deepClone(this.installArray)
  }
  //排序
  sortNumber(a, b) {
    //升序
    return a - b
  }
  //车轴数量出现安装位置
  carAxleAmountChange(value) {
    if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
      this.page.sensorAxle = []
      if (this.page.sensorChannel.length != 0) {
        for (var j = 0; j < this.page.sensorChannel.length; j++) {
          let mun = '0'
          this.page.sensorAxle.push(mun)
        }
      }
    }

    var array = []
    if (isNaN(value) == true) {
      this.jsonApiService.message('请输入数字')
      $('#carAxleAmount').val('')
      this.page.carAxleAmount = ''
      return
    } else if (value > 6) {
      this.jsonApiService.message('车轴数量不能大于6')
      $('#carAxleAmount').val('')
      this.page.carAxleAmount = ''
      return
    } else {
      if (value == '0') {
        this.jsonApiService.message('车轴数量不能为0')
        $('#carAxleAmount').val('')
        this.page.carAxleAmount = ''
        return
      } else if (value == '') {
        if (this.ChannelLen == 0 && this.page.carAxleAmount == '') {
          this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
          // this.installArray = this.page.sensorPosition
        } else {
          for (var i = 0; i < 6; i++) {
            var positionLMR = {
              index: i + 1,
              positionLMR: [
                {
                  position: 'L',
                  sensorChannel: []
                },
                {
                  position: 'M',
                  sensorChannel: []
                },
                {
                  position: 'R',
                  sensorChannel: []
                }
              ]
            }
            array.push(positionLMR)
          }
          this.installArray = this.deepClone(array)
          this.clearcheckChannel()
        }
      } else if (value == this.ChannelLen) {
        this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
        // this.showLocation(this.page.sensorChannel,this.installArray)
      } else {
        for (var i = 0; i < value; i++) {
          var positionLMR = {
            index: i + 1,
            positionLMR: [
              {
                position: 'L',
                sensorChannel: []
              },
              {
                position: 'M',
                sensorChannel: []
              },
              {
                position: 'R',
                sensorChannel: []
              }
            ]
          }
          array.push(positionLMR)
        }
        this.installArray = this.deepClone(array)
        this.clearcheckChannel()
      }
    }

    // for(let i=0;i<this.checkChannel.length;i++){
    // 	this.checkChannel[i].isDisable = false;
    // }
  }
  //清除安装位置轴数选中
  clearcheckChannel() {
    for (var a = 0; a < this.checkChannel.length; a++) {
      this.checkChannel[a].isDisable = false
    }
  }
  axisType: any = '' //打开那个方向传感器轴
  axisIndex: any = '' //打开那个传感器轴
  //添加传感器通道
  addinstall(index, type, modal) {
    this.axisType = type
    this.axisIndex = index
    if (this.page.sensorAmount) {
      modal.show()
    } else {
      this.jsonApiService.message('请先选择传感器')
    }
  }
  //选择弹框中的传感器通道
  choiceChannel(item, e) {
    for (let i = 0; i < this.checkChannel.length; i++) {
      if (item.mark == this.checkChannel[i].mark) {
        if (e.target.className.indexOf('check') != -1) {
          this.checkChannel[i].checked = false
        } else {
          this.checkChannel[i].checked = true
        }
      }
    }
  }
  //取消传感器弹框
  lgModalhide(modal) {
    this.axisType = ''
    this.axisIndex = ''
    modal.hide()
    for (let i = 0; i < this.checkChannel.length; i++) {
      if (this.checkChannel[i].checked) {
        this.checkChannel[i].checked = false
      }
    }
    // this.checkChannel = [];
  }
  //确定传感器
  lgModalConfirm(modal) {
    let newChannel = []
    for (let i = 0; i < this.checkChannel.length; i++) {
      if (this.checkChannel[i].checked) {
        this.checkChannel[i].isDisable = true
        if (this.axisType == 'left') {
          this.installArray[this.axisIndex - 1].positionLMR[0].sensorChannel.push(this.checkChannel[i].mark)
        } else if (this.axisType == 'middle') {
          this.installArray[this.axisIndex - 1].positionLMR[1].sensorChannel.push(this.checkChannel[i].mark)
        } else if (this.axisType == 'right') {
          this.installArray[this.axisIndex - 1].positionLMR[2].sensorChannel.push(this.checkChannel[i].mark)
        }
        // newChannel.push(this.checkChannel[i].mark)
      }
    }

    this.installArray[this.axisIndex - 1].positionLMR[0].sensorChannel.sort(this.sortNumber)
    this.installArray[this.axisIndex - 1].positionLMR[1].sensorChannel.sort(this.sortNumber)
    this.installArray[this.axisIndex - 1].positionLMR[2].sensorChannel.sort(this.sortNumber)
    this.lgModalhide(modal)
  }
  //删除选中的传感器
  cancelChannel(index, type, channel) {
    let valueList
    if (type == 'left') {
      valueList = this.installArray[index - 1].positionLMR[0].sensorChannel
      for (let i = 0; i < valueList.length; i++) {
        if (valueList[i] == channel) {
          valueList.splice(i, 1)
        }
      }
      this.installArray[index - 1].positionLMR[0].sensorChannel = this.deepClone(valueList)
    } else if (type == 'middle') {
      valueList = this.installArray[index - 1].positionLMR[1].sensorChannel
      for (let j = 0; j < valueList.length; j++) {
        if (valueList[j] == channel) {
          valueList.splice(j, 1)
        }
      }
      this.installArray[index - 1].positionLMR[1].sensorChannel = this.deepClone(valueList)
    } else if (type == 'right') {
      valueList = this.installArray[index - 1].positionLMR[2].sensorChannel
      for (let k = 0; k < valueList.length; k++) {
        if (valueList[k] == channel) {
          valueList.splice(k, 1)
        }
      }
      this.installArray[index - 1].positionLMR[2].sensorChannel = this.deepClone(valueList)
    }

    for (let l = 0; l < this.checkChannel.length; l++) {
      if (this.checkChannel[l].mark == channel) {
        this.checkChannel[l].isDisable = false
      }
    }
  }
  // 远程清零
  resetWeightToZero() {
    if (!this.deviceId) {
      this.jsonApiService.message('设备ID不能为空')
      return
    }
    this.jsonApiService.confirm_message('您确定要执行远程清零？').then(() => {
      let reqdata = 'protocolVersion=2&deviceId=' + this.deviceId + '&isAuto=false'
      this.jsonApiService.http('system/remotereset.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
      })
    })
  }
  //选择算法问题
  algorithmLisSelected(text) {
    for (let lis of this.algorithmQuestionList) {
      if (lis.text == text) {
        lis.selected = !lis.selected
      } else {
        lis.selected = false
      }
    }
  }
  //算法问题提交
  updataOrderStatus() {
    if (!this.deviceId) {
      this.jsonApiService.message('先选择车辆...')
      return
    }
    var proType2
    for (var i = 0; i < this.algorithmQuestionList.length; i++) {
      if (this.algorithmQuestionList[i].selected == true) {
        proType2 = this.algorithmQuestionList[i].programType
      }
    }

    if (!proType2) {
      this.jsonApiService.message('请选择问题分类')
      return
    }

    if (!this.startTime || !this.endTime) {
      this.jsonApiService.message('开始时间和结束时间不能为空...')
      return
    }

    this.jsonApiService.http('realtime/getRealTimeData.html', 'deviceId=' + this.deviceId).subscribe(result => {
      let params = {
        programType: proType2,
        deviceId: this.deviceId,
        version: result.data.version ? result.data.version : '',
        startDate: this.startTime,
        endDate: this.endTime,
        reason: '',
        exceptionType: '1',
        coefficient: result.data.coef ? result.data.coef : ''
      }
      let reqdata = ''
      for (let keys in params) {
        reqdata = reqdata + keys + '=' + params[keys] + '&'
      }
      reqdata = reqdata.substring(0, reqdata.length - 1)
      this.jsonApiService.http('dataExceptionRecord/addDataException.html', reqdata).subscribe(result2 => {
        this.jsonApiService.message(result2.message)
        if (result2.success) {
          // this.isDisable=false;
          //					this.load();
        }
      })
    })
  }

  isHold: boolean = true //是否展开工具箱
  fixedRecord: any = '' //待维修
  isFixedRecord: boolean //是否显示待维修
  waitFixedRecord: any = [] //最近一次维修 可能有多条
  gpsRecord: any = [] //GPS显示检测的数据
  //工具箱
  clickHold(value) {
    this.isFixedRecord = false
    if (!this.deviceId) {
      this.jsonApiService.message('车牌号码不能为空')
      return
    }
    if (!this.startTime || !this.endTime) {
      this.jsonApiService.message('开始时间或结束时间不能为空')
      return
    }
    this.isHold = value
    if (this.isHold == false) {
      this.fixedRecord = ''
      this.waitFixedRecord = []
      let reqdata = 'deviceId=' + this.deviceId + '&startDate=' + this.startTime + '&endDate=' + this.endTime
      this.jsonApiService.http2('system/queryDeviceRepairedRecordsByDeviceId.html', reqdata).subscribe(data => {
        if (data.success) {
          this.fixedRecord = data.data.fixedRecord
          this.waitFixedRecord = data.data.waitFixedRecord

          if (data.data.fixedRecord) {
            this.isFixedRecord = true
          }
        }
      })
    }
  }
  //检测GPS
  testingGPS() {
    if (!this.deviceId) {
      this.jsonApiService.message('车牌号码不能为空')
      return
    }
    let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime
    this.jsonApiService.http('stats/gpsDetection.html', reqdata).subscribe(data => {
      if (data.success) {
        if (data.data.length == 0) {
          this.jsonApiService.message('该GPS无异常')
        }
        this.gpsRecord = data.data
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //工具箱拖拽
  dragDrop() {
    //获取元素
    var dv = document.getElementById('holdAll')
    var x = 0
    var y = 0
    var l = 0
    var t = 0
    var isDown = false
    //鼠标按下事件
    dv.onmousedown = function (e) {
      //获取x坐标和y坐标
      x = e.clientX
      y = e.clientY

      //获取左部和顶部的偏移量
      l = dv.offsetLeft
      t = dv.offsetTop
      //开关打开
      isDown = true
      //设置样式
      dv.style.cursor = 'move'
    }
    //鼠标移动
    window.onmousemove = function (e) {
      if (isDown == false) {
        return
      }
      //获取x和y
      var nx = e.clientX
      var ny = e.clientY
      //计算移动后的左偏移量和顶部的偏移量
      var nl = nx - (x - l)
      var nt = ny - (y - t)

      dv.style.left = nl + 'px'
      dv.style.top = nt + 'px'
    }
    //鼠标抬起事件
    dv.onmouseup = function () {
      //开关关闭
      isDown = false
      dv.style.cursor = 'default'
    }
  }
  /**
   * 跳转服务费管理页面
   */
  goRenewal() {
    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    window.open(BaseURL + '#/system/renewal-manage')
  }

  /**
   * 待维修的删除
   */
  deleteRepaireRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      var reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepaired/delDeviceRepairedById.html', reqdata).subscribe(result => {
        this.jsonApiService.message(result.message)
        this.getTabData('4_1')
      })
    })
  }

  /**
   * 续费记录
   */
  renewForm: any = {
    carNumber: '',
    deviceId: '',
    payDate: '',
    renewalTime: '',
    remark: '',
    billType: '',
    installTime: '', //安装时间
    expire: '', //状态
    dockingTime: '', //对接时间
    remainingDay: '', //剩余天数
    renewCount: '', //缴费次数
    renewalDueTime: '', //服务到期时间
    warrantyExpirationTime: '' //保修到期时间
  }
  renewTableList: any = []
  renewalData: any = {
    companyId: '',
    id: ''
  }
  renewDialog(modal) {
    const that = this
    if (!this.deviceId) {
      this.jsonApiService.message('设备ID为空，请先设置设备ID')
      return
    }
    this.jsonApiService
      .http_get('projectCar/queryProjectCarInfoByDeviceId.html?deviceId=' + this.deviceId)
      .subscribe(result => {
        this.renewTableList = []
        if (result.data.length > 0) {
          this.renewForm.carNumber = result.data[0].carNumber
          this.renewForm.deviceId = result.data[0].deviceId
          this.renewForm.installTime = result.data[0].installTime
          this.renewTableList = result.data || []
          this.renewalData.companyId = ''
          this.renewalData.id = ''
          this.renewTableList.forEach((item, index) => {
            item.isChecked = false
            item.payDate = common.getNowTime()
            setTimeout(function () {
              that.initRenewalDate(index)
            }, 500)
            if (item.remainingDay.indexOf('-') != -1) {
              item.isSurplus = true
            } else {
              item.isSurplus = false
            }

            let remainingDay = item.remainingDay
            if (remainingDay.indexOf('-') != -1) {
              if (item.expire == '1' || item.expire == '0') {
                item.expireTime = '过期' + remainingDay.substring(1, remainingDay.length)
              } else if (item.expire == '2') {
                item.expireTime = '剩余' + remainingDay.substring(1, remainingDay.length)
              } else {
                item.expireTime = remainingDay
              }
            } else {
              if (item.expire == '1') {
                item.expireTime = '过期' + remainingDay
              } else if (item.expire == '2' || item.expire == '0') {
                item.expireTime = '剩余' + remainingDay
              } else {
                item.expireTime = remainingDay
              }
            }
          })
        }
        this.renewForm.remark = ''

        modal.show()
      })
  }
  // 续费详情的表单数据
  renewDetailsTable: any = []
  //查看续费详情
  see_renewDetails(row, modal) {
    modal.show()
    let reqdata = {
      dockingFactoryId: row.dockingFactoryId,
      deviceId: row.deviceId
    }
    // let reqdata = 'gridPager='+JSON.stringify(data);
    this.jsonApiService.http_obj('renewal/getRenewalInfo.html', reqdata).subscribe(data => {
      if (data.success) {
        this.renewDetailsTable = data.data
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //详情关闭
  renewDetailsClose(modal) {
    modal.hide()
  }
  //初始化日期
  initRenewalDate(index) {
    const that = this
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#payDate' + index)
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd hh:ii:ss',
            language: 'zh-CN',
            autoclose: true,
            bootcssVer: 3
          })
          .on('changeDate', function (e) {
            var date = e.date
            if (!date) {
              return
            }
            var time = common.getTimeMmss(date)
            that.renewTableList[index].payDate = time
          })
      })
    })
  }
  //选中
  rowRenewSelected(event, i) {
    if (event.target.checked) {
      this.renewTableList.forEach((item, index) => {
        if (index === i) {
          this.renewForm.remark = item.remark ? item.remark : ''
          this.renewForm.renewalTime = item.renewalTime
          this.renewForm.billType = item.isSameCompany === 1 ? 1 : 2
          this.renewForm.payDate = item.payDate
          this.renewalData.companyId = item.dockingFactoryId
          this.renewalData.id = item.id
          item.isChecked = true
        } else {
          item.isChecked = false
        }
      })
    } else {
      this.renewTableList[i].isChecked = false
      this.renewForm.remark = ''
      this.renewForm.renewalTime = ''
      this.renewForm.billType = ''
      this.renewalData.companyId = ''
      this.renewalData.id = ''
    }
  }
  //支付时间
  payDateChange(event, i) {
    this.renewTableList[i].payDate = event.target.value
    if (this.renewTableList[i].isChecked) {
      this.renewForm.payDate = event.target.value
    }
  }
  //续费时长
  renewalTimeChange(event, i) {
    this.renewTableList[i].renewalTime = event.target.value
    if (this.renewTableList[i].isChecked) {
      this.renewForm.renewalTime = event.target.value
    }
  }
  //备注
  remarkChange(event, i) {
    this.renewTableList[i].remark = event.target.value
    if (this.renewTableList[i].isChecked) {
      this.renewForm.remark = event.target.value
    }
  }
  cancelRenew(modal) {
    this.renewTableList.forEach((item, index) => {
      $('#payDate' + index).val('')
    })
    modal.hide()
  }
  renewSubmit(modal1, modal2) {
    if (!this.renewalData.companyId) {
      this.jsonApiService.message('请先选中缴费的公司')
      return
    }
    if (!this.renewForm.payDate) {
      this.jsonApiService.message('支付时间不能为空')
      return
    }
    if (!this.renewForm.renewalTime) {
      this.jsonApiService.message('续费时长不能为空')
      return
    }
    var url =
      '?payDate=' +
      this.renewForm.payDate +
      '&renewalTime=' +
      this.renewForm.renewalTime +
      '&remark=' +
      this.renewForm.remark +
      '&billType=' +
      this.renewForm.billType
    let renewalDataList = []
    renewalDataList.push(this.renewalData)
    this.jsonApiService
      .json_http('renewalTemp/uploadTempRecords.html' + url, JSON.stringify(renewalDataList))
      .subscribe(data => {
        if (data.success) {
          modal1.hide()
          this.showSubmitCheck(modal2, data.data)
        }
      })
  }

  /**
   * 提交核对
   */
  submitCheckTableData: any = [] //核对列表
  isSuccess: string = '' //提交前状态
  projectVersion: string = ''
  // 表单验证
  cleaningOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择厂区'
          }
        }
      },
      startInstallTime: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择开始时间'
          }
        }
      },
      installTime: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择结束时间'
          }
        }
      },
      dataCleanout: {
        validators: {
          notEmpty: {
            message: '请输入保留条数'
          }
        }
      }
    }
  }
  //显示
  showSubmitCheck(modal, version) {
    this.projectVersion = version
    this.check_table_search(modal)
  }
  //关闭
  cancelSubmitCheck(modal2, modal1) {
    this.isSuccess = ''
    this.submitCheckTableData = []
    this.projectVersion = ''
    modal2.hide()
    modal1.show()
  }
  queryCheckTable() {
    this.checkPageSize = 10
    this.checkCurPage = 1
    this.check_table_search('')
  }
  //查询
  check_table_search(modal) {
    let param = {
      pageSize: this.checkPageSize,
      nowPage: this.checkCurPage,
      parameters: {
        version: this.projectVersion,
        isSuccess: this.isSuccess
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('renewalTemp/pageList.html', reqdata).subscribe(result => {
      if (result.success) {
        this.submitCheckTableData = result.data.exhibitDatas
        if (modal) modal.show()
        for (let item of this.submitCheckTableData) {
          item['isChecked'] = false
        }
        this.allChecked = false
        this.selected = []
        this.numMessage = result.message
        this.rowId = ''
        this.checkTotalCounts = result.data.recordCount
      } else {
        this.numMessage = ''
      }
    })
  }
  //提交
  submitCheck(modal) {
    let isSubmit = true
    if (this.submitCheckTableData.length == 0) {
      this.jsonApiService.message('暂无需要提交核对的数据')
      return
    }

    for (let i = 0; i < this.submitCheckTableData.length; i++) {
      if (this.submitCheckTableData[i].isSuccess == 0) {
        isSubmit = false
        this.jsonApiService.message('列表中存在失败状态的数据')
        return
      }
    }

    if (isSubmit) {
      this.jsonApiService.http_obj('renewalTemp/submit.html', { version: this.projectVersion }).subscribe(result => {
        this.jsonApiService.message(result.message)
        if (result.success) {
          this.isSuccess = ''
          this.submitCheckTableData = []
          this.projectVersion = ''
          modal.hide()
        }
      })
    }
  }
  //删除
  delSubmitCheck(row) {
    this.jsonApiService.confirm_message('此操作将删除临时数据,确认要删除').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('renewalTemp/deleteRenewalTemp.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.check_table_search('')
        }
      })
    })
  }
  editcheckForm: any = {
    billType: '1',
    carNumber: '',
    companyId: '',
    companyName: '',
    renewalDate: '',
    createUser: '',
    dataSource: '3',
    deviceId: '',
    // endTime: "",
    errorMsg: '',
    firstServiceEndDate: '',
    id: '',
    isSuccess: '',
    projectId: '',
    remark: '',
    renewalCycle: '',
    startTime: '',
    version: ''
  }
  DockingList: any = []
  //编辑
  editSubmitCheck(row, modal) {
    // let reqdata = 'id=' + row.id;
    //获取编辑详情
    this.jsonApiService.http_get('renewalTemp/findRecordById.html?id=' + row.id).subscribe(data => {
      if (data.success) {
        this.DockingList = data.data.companys
        this.editcheckForm = data.data.record
        modal.show()
        // delete this.editcheckForm.changeDate
        this.initCreateDate()
      }
    })
  }
  //初始化日期
  initCreateDate() {
    var that = this
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#renewalDate')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd hh:ii:ss',
            language: 'zh-CN',
            autoclose: true,
            endDate: new Date()
          })
          .on('changeDate', function (e) {
            var date = e.date
            if (!date) {
              return
            }
            var time = common.getTimeMmss(date)
            // $("#createDate").datetimepicker("setStartDate", time);
            that.editcheckForm.renewalDate = time
            // that.countPay()
          })
      })
    })
  }
  dockingListChange() {
    for (let item of this.DockingList) {
      if (item.value === this.editcheckForm.companyId) {
        this.editcheckForm.companyName = item.companyName
        this.editcheckForm.firstServiceEndDate = item.firstTime
        this.editcheckForm.deviceId = item.deviceId
        this.editcheckForm.projectId = item.projectId
        this.editcheckForm.billType = item.isSameCompany === 1 ? 1 : 2
        // this.countPay()
      }
    }
  }
  //关闭编辑
  closeEditSubmitCheck(modal) {
    modal.hide()
  }
  //提交编辑
  submitEditSubmitCheck(modal) {
    if (!this.editcheckForm.renewalDate) {
      this.jsonApiService.message('缴费时间不能为空')
      return
    }
    if (!this.editcheckForm.renewalCycle) {
      this.jsonApiService.message('续费时长不能为空')
      return
    }
    this.jsonApiService.json_http('renewalTemp/updateRenewalTemp.html', this.editcheckForm).subscribe(result => {
      this.jsonApiService.message(result.message)
      if (result.success) {
        modal.hide()
        this.check_table_search('')
      }
    })
  }
  renewalCycleChange() {
    // this.countPay(); //计算
  }
  //计算续费
  countPay() {
    //续费时长=12，则直接在原到期时间上，增加一年
    if (this.editcheckForm.renewalCycle == 12) {
      let date1 = parseInt(this.editcheckForm.firstServiceEndDate.substring(0, 4)) + 1
      let date2 = this.editcheckForm.firstServiceEndDate.substring(4, this.editcheckForm.firstServiceEndDate.length)
      this.editcheckForm.endTime = date1 + date2
    } else {
      if (this.editcheckForm.renewalCycle) {
        var str2 = this.editcheckForm.renewalDate.substr(10, this.editcheckForm.renewalDate.length - 1)
        var str1 = this.editcheckForm.renewalDate.replace(/-/g, '/') //'2018/01/01 00:00:00'
        var date = new Date(Date.parse(str1)) //date格式的时间类型
        var nowDate = this.addMonth(date, this.editcheckForm.renewalCycle) //date格式的时间类型
        this.editcheckForm.endTime = this.format(nowDate) + str2
      }
    }
  }

  addMonth(date, addMonth) {
    var y = date.getFullYear()
    var m = date.getMonth()
    var nextY = y
    var nextM = m
    //如果当前月+要加上的月>11 这里之所以用11是因为 js的月份从0开始
    if (m + parseInt(addMonth) > 11) {
      nextY = y + 1
      nextM = m + parseInt(addMonth) - 12
    } else {
      nextM = date.getMonth() + parseInt(addMonth)
    }
    var daysInNextMonth = this.daysInMonth(nextY, nextM)
    var day = date.getDate()
    if (day > daysInNextMonth) {
      day = daysInNextMonth
    }
    return new Date(nextY, nextM, day)
  }
  daysInMonth(year, month) {
    if (month == 1) {
      if (year % 4 == 0 && year % 100 != 0) return 29
      else return 28
      // 测试
    } else if ((month <= 6 && month % 2 == 0) || (month > 8 && month % 2 == 1)) return 31
    else return 30
  }
  format(nowDate) {
    var format = 'yyyy-MM-dd'
    var date = {
      'M+': nowDate.getMonth() + 1,
      'd+': nowDate.getDate(),
      'h+': nowDate.getHours(),
      'm+': nowDate.getMinutes(),
      's+': nowDate.getSeconds(),
      'q+': Math.floor((nowDate.getMonth() + 3) / 3),
      'S+': nowDate.getMilliseconds()
    }
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (nowDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in date) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? date[k] : ('00' + date[k]).substr(('' + date[k]).length)
        )
      }
    }
    return format
  }
  numMessage: any = '' //显示数量
  // 核对数据的导出
  exportCheckData() {
    var params = {
      version: this.projectVersion,
      isSuccess: this.isSuccess,
      ids: this.rowId
    }
    common.exprotDataFile(params, 'gridPager', config.BaseURL + 'renewalTemp/exportRenewalTempData.html')
  }
  //批量删除
  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowId: string = '' //批量
  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.submitCheckTableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowId = ''
    } else {
      var temArr = []
      for (let item of this.submitCheckTableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.rowId)
      }
      this.rowId = temArr.join(',')
    }
  }
  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowId = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.submitCheckTableData.length ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }
  batchDelete() {
    if (this.selected.length && this.rowId != '') {
      this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
        let reqdata = 'id=' + this.rowId
        this.jsonApiService.http('renewalTemp/deleteRenewalTemp.html', reqdata).subscribe(data => {
          this.jsonApiService.message(data.message)
          this.check_table_search('')
        })
      })
    } else {
      this.jsonApiService.message('请选中最少一条数据')
    }
  }

  checkCurPage: number = 1
  checkPageSize: number = 10
  checkTotalCounts: number = 0 //分页总条数
  // 分页回调
  checkPaginate(e) {
    this.checkCurPage = e.page + 1
    this.checkPageSize = e.rows
    this.check_table_search('')
  }
  // 刷新表
  checkRefresh() {
    this.check_table_search('')
  }

  syncValidator = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      dockingFactory: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择同步厂区'
          }
        }
      }
    }
  }

  projectCarFrom = {
    id: '',
    deviceId: '',
    carNumber: '',
    installFactoryName: '', // 安装厂区
    dockedFactoryName: '', // 已对接厂区名称
    dockedFactoryId: '', // 已对接厂区ID
    installFactoryId: '',
    dockingFactoryName: '', // 对接厂区
    dockingFactoryId: '',
    dockingTime: '',
    synRenew: ''
  }

  isResetSelected: boolean = false

  //对接角色
  userList: any = []

  RoleXxplain = ''
  dockingRole = ''
  // 根据对接厂区拉取配饰对接的角色数据
  getRoleBycompanyConfig(companyId) {
    const that = this
    that.userList = []
    that.jsonApiService
      .http_obj('projectDocking/getRoleInfoByCompany.html', { companyId: companyId })
      .subscribe(data => {
        if (data.success) {
          const userList = data.data
          const selectdata = []
          if (userList.length == 0) {
            this.RoleXxplain = '对接厂区没有配置对接角色,请先配置项目对接角色'
            that.jsonApiService.message('对接厂区没有配置对接角色,请先配置项目对接角色')
          } else {
            for (var i = 0; i < userList.length; i++) {
              var obj = {
                id: userList[i].roleId,
                text: userList[i].roleName,
                check: false
              }
              selectdata[i] = obj
            }
            that.userList = selectdata
            //数据为一个时候 默认选中
            if (that.userList.length == 1) {
              that.userList[0].check = true
              this.dockingRole = that.userList[0].id
            }
          }
        }
      })
  }
  checkBoxRole(value, id) {
    const userData = []
    for (let i = 0; i < this.userList.length; i++) {
      if (this.userList[i].id == id) {
        if (value.checked) {
          this.userList[i].check = true
        } else {
          this.userList[i].check = false
        }
      }
    }

    for (let j = 0; j < this.userList.length; j++) {
      if (this.userList[j].check) {
        userData.push(this.userList[j].id)
      }
    }

    this.dockingRole = userData.join(',')
    $('#projectCarFrom').data('bootstrapValidator').resetForm()
  }

  // 路由跳转
  jumpToPage(e, url) {
    $('#projectCarModal').modal('hide')
    e.stopPropagation()
    this.router.navigate([url])
  }

  syncFactory(modal) {
    const self = this
    const deviceId = self.deviceId
    const projectCarFrom = self.projectCarFrom
    if (deviceId == '') {
      self.message('请选择车牌号')
      return
    }
    $('#projectCarFrom').data('bootstrapValidator').resetForm()

    const reqdata = 'deviceId=' + deviceId
    self.jsonApiService.http('projectCar/getProjectCarByDeviceId.html', reqdata).subscribe(result => {
      const { data } = result

      projectCarFrom.installFactoryName = data.installFactoryName
      projectCarFrom.installFactoryId = data.installFactoryId
      // 结果返回的已对接厂区内容，对接厂区需要重新选择
      projectCarFrom.dockedFactoryName = data.dockingFactoryName
      projectCarFrom.dockedFactoryId = data.dockingFactoryId

      projectCarFrom.deviceId = deviceId
      projectCarFrom.carNumber = data.carNumber

      this.dockingRole = ''
      self.isResetSelected = false
      projectCarFrom.synRenew = '0'
      projectCarFrom.dockingTime = self.getNowFormatDate()
      modal.show()
    })
  }

  resetSelectClick() {
    this.isResetSelected = !this.isResetSelected
  }

  //校验重复
  checkValue() {
    const that = this
    const projectCarFrom = that.projectCarFrom
    const dataSource = {
      deviceId: projectCarFrom.deviceId,
      dockingFactoryId: projectCarFrom.dockingFactoryId
    }
    if (projectCarFrom.deviceId && projectCarFrom.dockingFactoryId) {
      that.jsonApiService.http_obj('projectCar/validate.html', dataSource).subscribe(data => {
        if (data.valid == false) {
          that.jsonApiService.message(data.message)
          setTimeout(function () {
            projectCarFrom.dockingFactoryName = ''
            projectCarFrom.dockingFactoryId = ''
          }, 100)
        }
      })
    }
  }
  projectCarClose(modal) {
    modal.hide()
    const projectCarFrom = this.projectCarFrom
    projectCarFrom.installFactoryName = ''
    projectCarFrom.installFactoryId = ''

    projectCarFrom.dockedFactoryName = ''
    projectCarFrom.dockedFactoryId = ''

    projectCarFrom.dockingFactoryName = ''
    projectCarFrom.dockingFactoryId = ''
    projectCarFrom.deviceId = ''
    projectCarFrom.carNumber = ''
    projectCarFrom.dockingTime = ''

    this.dockingRole = ''
  }
  syncCompanySelect(data) {
    const projectCarFrom = this.projectCarFrom
    this.getRoleBycompanyConfig(data.companyId)
    projectCarFrom.dockingFactoryId = data.companyId || ''
    projectCarFrom.dockingFactoryName = data.companyName
    if (projectCarFrom.deviceId && projectCarFrom.dockingFactoryId) {
      this.checkValue()
    }
  }

  //提交更新
  projectCarSubmit(modal) {
    const projectCarFrom = this.projectCarFrom
    projectCarFrom.synRenew = this.isResetSelected ? '1' : '0'
    $('#projectCarFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#projectCarFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      if (this.dockingRole) {
        let reqData = {
          roleIds: this.dockingRole,
          deviceId: projectCarFrom.deviceId,
          carNumber: projectCarFrom.carNumber
        }
        this.jsonApiService.http_obj('projectDocking/distributionCarToRole.html', reqData).subscribe(data => { })
      }
      // 项目新增
      this.jsonApiService.http_obj('projectCar/add.html', projectCarFrom).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.projectCarClose(modal)
        }
      })
    }
  }

  getNowFormatDate() {
    const date = new Date()
    const seperator1 = '-'
    const seperator2 = ':'
    const month = date.getMonth() + 1
    const strDate = date.getDate()
    const strHours = date.getHours()
    const strMinutes = date.getMinutes()
    const strSeconds = date.getSeconds()
    let month_str
    if (month >= 1 && month <= 9) {
      month_str = '0' + month
    } else {
      month_str = month
    }
    let strDate_str
    if (strDate >= 0 && strDate <= 9) {
      strDate_str = '0' + strDate
    } else {
      strDate_str = strDate
    }
    let strHours_str
    if (strHours >= 0 && strHours <= 9) {
      strHours_str = '0' + month
    } else {
      strHours_str = strHours
    }
    let strMinutes_str
    if (strMinutes >= 0 && strMinutes <= 9) {
      strMinutes_str = '0' + strMinutes
    } else {
      strMinutes_str = strMinutes
    }
    let strSeconds_str
    if (strSeconds >= 0 && strSeconds <= 9) {
      strSeconds_str = '0' + strSeconds
    } else {
      strSeconds_str = strSeconds
    }

    //
    const currentdate =
      date.getFullYear() +
      seperator1 +
      month_str +
      seperator1 +
      strDate_str +
      ' ' +
      strHours_str +
      seperator2 +
      strMinutes_str +
      seperator2 +
      strSeconds_str
    return currentdate
  }

  groupMessageFrom = {
    deviceId: '',
    carNumber: '',
    installFactoryName: '', // 安装厂区
    installFactoryId: '',
    groupName: '', // 群名称
    questioner: '', // 	提问题的人
    question: '', // 问题
    type: '', // 归类
    typeDesc: '', // 归类描述
    projectName: '', // 项目名称
    projectId: '', // 项目ID
    remark: '' // 备注
  }
  // 获取父级公司列表
  inputApi: string = 'company/getParentCompany.html'

  groupMsgValidator = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      groupNameInput: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入群名称'
          }
        }
      },
      questionerInput: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入提问题的人'
          }
        }
      },
      questionInput: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入提问题'
          }
        }
      },
      groupMsgType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择归类'
          }
        }
      }
    }
  }

  openGroupMessageView(modal) {
    const self = this
    const groupMessageFrom = self.groupMessageFrom
    const deviceId = self.deviceId || ''
    $('#groupMessageFrom').data('bootstrapValidator').resetForm()
    if (deviceId) {
      const reqdata = 'deviceId=' + deviceId
      self.jsonApiService.http('car/getFactoryAndProject.html', reqdata).subscribe(data => {
        groupMessageFrom.deviceId = deviceId
        groupMessageFrom.carNumber = data.carNumber
        groupMessageFrom.installFactoryName = data.installFactoryName
        groupMessageFrom.installFactoryId = data.installFactoryId
        groupMessageFrom.projectId = data.projectId
        groupMessageFrom.projectName = data.projectName
        modal.show()
      })
    } else {
      modal.show()
    }
  }

  massageCompanySelected(data) {
    const groupMessageFrom = this.groupMessageFrom
    groupMessageFrom.projectId = data.companyId || ''
    groupMessageFrom.projectName = data.companyName
  }

  groupMessageClose(modal) {
    const groupMessageFrom = this.groupMessageFrom
    groupMessageFrom.deviceId = ''
    groupMessageFrom.carNumber = ''
    groupMessageFrom.installFactoryName = ''
    groupMessageFrom.installFactoryId = ''
    groupMessageFrom.groupName = ''
    groupMessageFrom.questioner = ''
    groupMessageFrom.question = ''
    groupMessageFrom.type = ''
    groupMessageFrom.typeDesc = ''
    groupMessageFrom.projectName = ''
    groupMessageFrom.projectId = ''
    groupMessageFrom.remark = ''
    modal.hide()
  }

  resetGroupMessage() {
    const groupMessageFrom = this.groupMessageFrom
    groupMessageFrom.groupName = ''
    groupMessageFrom.questioner = ''
    groupMessageFrom.question = ''
    groupMessageFrom.type = ''
    groupMessageFrom.typeDesc = ''
    groupMessageFrom.projectName = ''
    groupMessageFrom.projectId = ''
    groupMessageFrom.remark = ''
  }

  groupMessageSubmit() {
    const groupMessageFrom = this.groupMessageFrom
    const newGroupMessageFrom = { ...groupMessageFrom, queStartTime: this.startTime, queEndTime: this.endTime }
    newGroupMessageFrom.groupName = encodeURIComponent(newGroupMessageFrom.groupName)
    const that = this
    const msgHistoryList = that.msgHistoryList
    $('#groupMessageFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#groupMessageFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      // 项目新增
      that.jsonApiService.http_obj('groupMessage/addGroupMessage.html', newGroupMessageFrom).subscribe(data => {
        that.jsonApiService.message(data.message)
        if (data.success) {
          groupMessageFrom.projectName = ''
          groupMessageFrom.projectId = ''
          groupMessageFrom.remark = ''
          delete newGroupMessageFrom.deviceId
          delete newGroupMessageFrom.carNumber
          delete newGroupMessageFrom.installFactoryName
          delete newGroupMessageFrom.installFactoryId
          newGroupMessageFrom.groupName = decodeURIComponent(newGroupMessageFrom.groupName)
          msgHistoryList.push(newGroupMessageFrom)
          if (msgHistoryList.length > 3) {
            msgHistoryList.shift()
          }
          setLocal('hd-optimization-msgHistory', msgHistoryList)
        }
      })
    }
  }

  typeEnum = [
    '',
    '设备状态查询',
    '订单-传感器问题',
    '订单-GPS问题',
    '订单-离线',
    '订单-算法问题',
    '订单-磅单问题',
    '订单-数据正常',
    '续费',
    '同步',
    '更改ID',
    '移机-改车牌',
    '临时放行',
    '录车'
  ]

  msgTypeChange() {
    this.groupMessageFrom.typeDesc = this.typeEnum[this.groupMessageFrom.type]
  }

  showHistoryModal(modal) {
    modal.show()
  }

  closeModal(modal) {
    modal.hide()
  }
  copyHistory(item, modal) {
    for (const key in item) {
      if (Object.prototype.hasOwnProperty.call(item, key)) {
        const element = item[key]
        this.groupMessageFrom[key] = element
      }
    }
    modal.hide()
  }

  /**
   * 限制进厂弹框
   *
   */
  lgisPush: any = '0' //是否进厂限制 默认不限制
  isPushTime: number = 6
  isPushTimeFlag: string = ''
  limitRowId = ''
  autoReset(modal, row) {
    this.lgisPush = row.isPush.toString()
    this.isPushTime = 6
    modal.show()
    this.limitRowId = row.id
  }

  // 待维修状态设置限制进场回调
  problemRestrictCallback() {
    this.jsonApiService.http_obj('car/getCarInfoByDeviceId.html', { deviceId: this.deviceId }).subscribe(data => {
      if (data.success) {
        const result = data.data
        this.faultProblemResults = result.faultProblemResults.map(item => ({
          ...item,
          id: item.linkWaitRepairRecordId,
          isPush: item.limitEnterFactoryCode
        }))
      }

    })
  }

  //确定批量进厂限制
  submitLimitModal(modal) {
    // modal.show()
    let isPush = this.lgisPush == 'time' ? '0' : this.lgisPush
    let isPushTime = this.lgisPush == 'time' ? this.isPushTime : ''
    let reqdata = {
      ids: this.limitRowId,
      isPush: isPush,
      time: isPushTime
    }
    this.jsonApiService.http_obj('deviceRepaired/enterFactoryLimitBatch.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        modal.hide()
        // 设备信息弹框显示待维修列表的话，刷新
        if ($('#waitRepaired').is(':visible')) {
          this.getTableDataTab('4_1')
        }
        this.problemRestrictCallback()
      }
    })
  }
  //取消批量进厂限制
  // cancelModalHide(modal) {
  //   modal.hide()
  // }
  //自定义限制,校验非空值,默认6小时,不允许为空
  inputChange() {
    this.isPushTime = Math.abs(Math.floor(this.isPushTime))
    if (!this.isPushTime) {
      this.isPushTime = 6
    }
  }
  // 取消限制
  cancelRestrict(row) {
    this.jsonApiService.confirm_message('确定要取消自定义限制[' + row.restrictTime + '后限制]?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepaired/removeRestrictions.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.getTableDataTab('4_1')
        }
      })
    })
  }
  //调整服务器到期和保修到期内容显示
  carRenewalInfo: any = '' // 车辆的到期时间信息
  getRenewTime() {
    this.jsonApiService
      .http_get('projectCar/queryProjectCarInfoByDeviceId.html?deviceId=' + this.deviceId)
      .subscribe(result => {
        if (result.data && result.data.length > 0) {
          const dataList = result.data
          let now = new Date().getTime()
          let obj = {
            renewalFactoryList: [],
            sensorRepairInfoList: [], //传感器通道
            warrantyExpirationTime: '', //主机到期时间
            isHostDate: false as Boolean, //主机到期时间是否到期
          }
          dataList.forEach((item, index) => {
            let renewalFactoryObj = {
              factoryName: '',
              renewalDueTime: '',
              isExpired: false as Boolean, //服务到期时间是否到期
              status: item.status// 厂区停用状态 0：未停用, 1：停用
            }
            if (item.dockingFactoryId === item.installFactoryId) {
              renewalFactoryObj.factoryName = item.installFactoryName
            } else {
              renewalFactoryObj.factoryName = item.dockingFactoryName
            }
            renewalFactoryObj.renewalDueTime = item.renewalDueTime
            let overlineDate = new Date(item.renewalDueTime).getTime()
            //判断服务到期时间是否过期
            if (overlineDate > now) {
              renewalFactoryObj.isExpired = false
            } else {
              renewalFactoryObj.isExpired = true
            }
            obj.renewalFactoryList.push(renewalFactoryObj) //服务到期时间list
            //取第一条数据
            if (index === 0) {
              obj.warrantyExpirationTime = item.warrantyExpirationTime
              let hostDate = new Date(item.warrantyExpirationTime).getTime()
              //判断主机保修到期时间是否过期
              if (hostDate > now) {
                obj.isHostDate = false
              } else {
                obj.isHostDate = true
              }
              //取出通道时间
              if (item.sensorRepairInfoList && item.sensorRepairInfoList.length > 0) {
                item.sensorRepairInfoList.forEach((list, childIndex) => {
                  let sensorRepairObj = {
                    sensorNumber: null, //通道数
                    warrantyExpirationTime: '', //通道时间
                    orNotExpired: false as Boolean //是否过期
                  }
                  sensorRepairObj.sensorNumber = list.sensorNumber
                  sensorRepairObj.warrantyExpirationTime = list.warrantyExpirationTime
                  let sensorDate = new Date(list.warrantyExpirationTime).getTime()
                  //判断传感器通道保修到期时间是否过期
                  if (sensorDate > now) {
                    sensorRepairObj.orNotExpired = false
                  } else {
                    sensorRepairObj.orNotExpired = true
                  }
                  obj.sensorRepairInfoList.push(sensorRepairObj)
                })
              }
            }
            this.carRenewalInfo = obj
          })
        } else {
          this.carRenewalInfo = ''
        }
      })
  }

  // 传感器白名单
  sensorBypassValidatorOptions = {
    excluded: [":disabled"],
    fields: {
      deviceId: {
        validators: {
          notEmpty: {
            message: '请选择车辆'
          }
        }
      },
      status: {
        validators: {
          notEmpty: {
            message: '请选择白名单时长'
          }
        }
      },
      days: {
        validators: {
          notEmpty: {
            message: '请输入自定义天数'
          }
        }
      },
      // describe: {
      //   validators: {
      //     notEmpty: {
      //       message: '请输入白名单原因'
      //     }
      //   }
      // },
    }
  }

  sensorBypassModel = {
    deviceId: '',
    carNumber: '',
    status: '', // 白名单状态（1长期 2自定义天数 3取消白名单）
    days: null,
    describe: ''
  }

  handleSensorBypassSetting(modal, row) {
    $("#setFrequencyFrom").data('bootstrapValidator').resetForm();
    const { deviceId, carNumber } = row
    // 重置数据，写入车辆信息
    this.sensorBypassModel = {
      deviceId,
      carNumber,
      status: '', // 白名单状态（1长期 2自定义天数 3取消白名单）
      days: null,
      describe: ''
    }
    modal.show()
  }
  //自定义限制,校验非空值,默认6小时,不允许为空
  sensorBypassInputChange() {
    this.sensorBypassModel.days = Math.abs(Math.floor(this.sensorBypassModel.days))
  }
  // 时长选中项改变，清空天数
  handleSersonBypassStatusChange() {
    this.sensorBypassModel.days = null
  }

  editSensorBypassModal(modal) {
    $('#setFrequencyFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setFrequencyFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      if (this.sensorBypassModel.status === '2' && !this.sensorBypassModel.days) {
        this.jsonApiService.message('请输入自定义天数')
        return
      }
      const sensorBypassModel = this.sensorBypassModel
      const data = Object.keys(sensorBypassModel).reduce((prev, key) => {
        const val = sensorBypassModel[key]
        if (val) {
          prev[key] = val
        }
        return prev
      }, {})
      this.jsonApiService.http_obj('deviceCheck/addSensorCheckWhiteList.html', data).subscribe(data => {
        this.jsonApiService.message(data.message);
        if (data.success) {
          this.sensorBypassModel = {
            deviceId: '',
            carNumber: '',
            status: '', // 白名单状态（1长期 2自定义天数 3取消白名单）
            days: null,
            describe: ''
          }
          modal.hide()
        }
      })
    }
  }

  handleJumpFault() {
    // 设置查看传感器白名单
    common.setCookie('__OPEN_WHITELIST__', "OPTIMIZATION")
    // 跳转
    this.router.navigate(['/device-management/fault']);
  }

}
